Home > Software design >  Ruby shorthand for adding items to array in each loop
Ruby shorthand for adding items to array in each loop

Time:10-20

I feel like i've seen this question somewhere before but i cannot find it and i'm pretty sure ruby has a one liner for looping over something and adding the items to an array:

items = []
some_stuff.each do |stuff|
  items << stuff
end
items

CodePudding user response:

this way?

items = some_stuff.inject([]) { |acc, item| acc   [item] }

obviously this exact snippet doesn't make sense because it's another array with the same value, you could just dup some_stuff, but I think can help you anyway

CodePudding user response:

Is this what you are looking for?

some_stuff=[1,2,3,4,6,7]

Code

items=some_stuff.each_with_object([]){|value,items|items.push(value)}
p items

Output

[1, 2, 3, 4, 6, 7]
  •  Tags:  
  • ruby
  • Related