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
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
[item] and one as the result of acc + [item].If some_stuff responds to each, then it very likely also conforms to the Enumerable protocol. (It would be silly not to, since each is all you need to support the Enumerable protocol via include Enumerable.)
The Enumerable protocol includes the method Enumerable#to_a, which returns the elements of the Enumerable as an Array:
to_a→arrayReturns an array containing the items in
self:(0..4).to_a # => [0, 1, 2, 3, 4]
So, assuming that some_stuff really does conform to the Enumerable protocol, all you need to do is
items = some_stuff.to_a
However, unless you absolutely need the specific features an Array provides, there is no need to even do this. If some_stuff really does conform to the Enumerable protocol, then most of the methods that you would use on the Array already exist on some_stuff as well, and they may even be more efficient because some_stuff knows more about what its internal structure is and what the structure of the elements is than Array does.
There is often no need to convert an Enumerable to an Array.
Enumerable#reduceorEnumerable#each_with_objectwould do the jobreduceis only for summation? Reduce is Ruby's answer tofoldHOF and it can do this job perfectly fine. Which one to pick is just a matter of personal preferences or conventionsitems = some_stuff.dupis all you need. Or maybeitems.concat(some_stuff)to append to an existing array.Enumerable#map, e.g.items = some_stuff.map { |stuff| stuff.whatever }? Your initial example is probably too simplified for what you actually intend to do.