(一元)*运算符在此Ruby代码中做什么? [英] What does the (unary) * operator do in this Ruby code?
问题描述
给出Ruby代码
line = "first_name=mickey;last_name=mouse;country=usa"
record = Hash[*line.split(/=|;/)]
除了*
运算符外,我理解第二行中的所有内容-它在做什么,相关文档在哪里? (您可能会猜到,搜索这种情况非常困难...)
*
是 splat 运算符.
它将Array
扩展为参数列表,在本例中为Hash.[]
方法的参数列表. (更确切地说,它扩展了对to_ary
/to_a
或Ruby 1.9中的to_a
作出响应的任何对象.)
为了说明,以下两个语句是相等的:
method arg1, arg2, arg3
method *[arg1, arg2, arg3]
它也可以在不同的上下文中使用,以捕获方法定义中所有剩余的方法参数.在这种情况下,它不会扩展,而是结合在一起:
def method2(*args) # args will hold Array of all arguments
end
Given the Ruby code
line = "first_name=mickey;last_name=mouse;country=usa"
record = Hash[*line.split(/=|;/)]
I understand everything in the second line apart from the *
operator - what is it doing and where is the documentation for this? (as you might guess, searching for this case is proving hard...)
The *
is the splat operator.
It expands an Array
into a list of arguments, in this case a list of arguments to the Hash.[]
method. (To be more precise, it expands any object that responds to to_ary
/to_a
, or to_a
in Ruby 1.9.)
To illustrate, the following two statements are equal:
method arg1, arg2, arg3
method *[arg1, arg2, arg3]
It can also be used in a different context, to catch all remaining method arguments in a method definition. In that case, it does not expand, but combine:
def method2(*args) # args will hold Array of all arguments
end
Some more detailed information here.
这篇关于(一元)*运算符在此Ruby代码中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!