我是Ruby的新手并试图阅读一些代码。我无法弄清楚*
符号究竟是什么告诉Ruby解释器在这个片段中做了什么:
[1]> items = [:one, :two, :three]
=> [:one, :two, :three]
[2]> x = Hash[*items.map { |item| [item, item.to_s+' !!'] }.flatten ]
=> {:one=>"one !!", :two=>"two !!", :three=>"three !!"}
答案 0 :(得分:3)
假设我在Ruby中有一些方法:
def a_method(a,b,c)
"#{a} #{b} #{c}"
end
和一个数组:
arr = [1,2,3]
我想将数组的3个元素传递给方法。这将产生错误:
a_method(arr) # wrong number of arguments
那我该怎么办?我当然可以这样做:
a_method(arr[0], arr[1], arr[2])
但是使用*" splat"这是一种更简单的方法。操作者:
a_method(*arr)
基本上,您将获得与上述相同的效果。把它想象成一个"捷径" "转换"在调用方法时使用时,每个数组元素都成为方法参数。这个splat操作符有点复杂,因为它在不同的地方使用时表现不同(你对这个主题有lots of useful articles)。
在您的示例中,基本上,在完成以下表达式之后:
items.map { |item| [item, item.to_s+' !!'] }.flatten
它产生:
[:one, "one !!", :two, "two !!", :three, "three !!"]
并使用" splat"将此数据传递给Hash
方法。运算符,因为Hash
不接受单个数组作为参数:
arr = ['a', 'b', 'c', 'd']
p Hash{arr} #=> error, wrong number of arguments
p Hash[*arr] #=> {"a"=>"b", "c"=>"d"}
答案 1 :(得分:1)
没有*
,你得到
Hash[[:one, "one !!", :two, "two !!", :three, "three !!"]]
不会起作用。 *
" splats"将数组转换为一系列参数,给你:
Hash[:one, "one !!", :two, "two !!", :three, "three !!"]
答案 2 :(得分:1)
它的功能是将数组转换为函数的各个参数。
给定一个接受参数的函数......
def my_func(a, b, c)
end
您可以通过直接指定参数来调用具有三个参数的函数:my_func(1,2,3)
或者,如果你有一个包含函数参数的数组,你可以使用splat运算符“展开”数组来填充函数的参数:
args = [1,2,3]
my_func(*args) # identical to my_func(1,2,3)
在您的特定情况下,Hash上有一个名为[]
的类方法,它接受可变数量的参数。代码使用map
生成数组,然后将数组的每个元素作为参数传递给Hash[]
。