本文介绍了红宝石:"p * 1..10"中的星号是什么意思是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
线
p *1..10与...完全相同
(1..10).each { |x| puts x }为您提供以下输出:
$ ruby -e "p *1..10" 1 2 3 4 5 6 7 8 9 10例如,当与textmate一起使用时,这是一个很好的捷径,但是星号有什么作用?这是如何运作的?在网上找不到任何东西...
it's a great shortcut when working with textmate for example, but what does the asterisk do? how does that work? couldn't find anything on the net...
推荐答案它是 splat运算符.您会经常看到它用于将数组拆分为函数的参数.
It's the splat operator. You'll often see it used to split an array into parameters to a function.
def my_function(param1, param2, param3) param1 + param2 + param3 end my_values = [2, 3, 5] my_function(*my_values) # returns 10更常见的是,它用于接受任意数量的参数
More commonly it is used to accept an arbitrary number of arguments
def my_other_function(to_add, *other_args) other_args.map { |arg| arg + to_add } end my_other_function(1, 6, 7, 8) # returns [7, 8, 9]它也适用于多个分配(尽管这两个语句在没有splat的情况下都可以使用):
It also works for multiple assignment (although both of these statements will work without the splat):
first, second, third = *my_values *my_new_array = 7, 11, 13在您的示例中,这两个是等效的:
For your example, these two would be equivalent:
p *1..10 p 1, 2, 3, 4, 5, 6, 7, 8, 9, 10更多推荐
红宝石:"p * 1..10"中的星号是什么意思是
发布评论