ruby: what does the asterisk in “p *1..10” mean

后端 未结 1 1175
陌清茗
陌清茗 2021-01-31 15:25

the line

p *1..10

does exactly the same thing as

(1..10).each { |x| puts x }

which gives you the following ou

相关标签:
1条回答
  • 2021-01-31 15:59

    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]
    

    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
    
    0 讨论(0)
提交回复
热议问题