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

前端 未结 3 1542
隐瞒了意图╮
隐瞒了意图╮ 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:43

    The splat operator unpacks an array passed to a function so that each element is sent to the function as an individual parameter.

    A simple example:

    >> def func(a, b, c)
    >>   puts a, b, c
    >> end
    => nil
    
    >> func(1, 2, 3)  #we can call func with three parameters
    1
    2
    3
    => nil
    
    >> list = [1, 2, 3]
    => [1, 2, 3]
    
    >> func(list) #We CAN'T call func with an array, even though it has three objects
    ArgumentError: wrong number of arguments (1 for 3)
        from (irb):12:in 'func'
        from (irb):12
    
    >> func(*list) #But we CAN call func with an unpacked array.
    1
    2
    3
    => nil
    

    That's it!

提交回复
热议问题