I have a method that returns a hash. I want to repeat through this method five times, collecting the results into an array. Right now, I'm trying it like this:
votes = 5.times.collect{ create_vote }.inject{|memo, vote| memo << vote}
This doesn't work, and I believe it's failing because memo isn't an array. Is there another approach I could take to this problem?
Yes:
votes = 5.times.collect { create_vote }
More generally, use each_with_object:
votes = 5.times.collect { create_vote }.each_with_object([]) {|o,memo| memo << o }
each_with_object is a method added because Ruby Core found that using inject in the way you intended to use it was very common.
Use #map on a range instead of #times on a fixnum
(0..5).map { create_vote }
Or, map an array from the times
5.times.map { create_vote }
Each will give you an array with 5 elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With