How to initialize an array in one step using Ruby?

后端 未结 9 736
情话喂你
情话喂你 2021-01-30 00:08

I initialize an array this way:

array = Array.new
array << \'1\' << \'2\' << \'3\'

Is it possible to do that in one s

9条回答
  •  醉话见心
    2021-01-30 00:20

    To prove There's More Than One Six Ways To Do It:

    plus_1 = 1.method(:+)
    Array.new(3, &plus_1) # => [1, 2, 3]
    

    If 1.method(:+) wasn't possible, you could also do

    plus_1 = Proc.new {|n| n + 1}
    Array.new(3, &plus_1) # => [1, 2, 3]
    

    Sure, it's overkill in this scenario, but if plus_1 was a really long expression, you might want to put it on a separate line from the array creation.

提交回复
热议问题