What does the (unary) * operator do in this Ruby code?

前端 未结 3 1633
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 17:18

Given the Ruby code

line = \"first_name=mickey;last_name=mouse;country=usa\" 
record = Hash[*line.split(/=|;/)] 

I understand everything i

3条回答
  •  [愿得一人]
    2020-11-22 17:55

    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.

提交回复
热议问题