nullnullnull nullnullnull - 4 months ago 12
Ruby Question

Ruby: Repeating a Method Multiple Times and Collecting Results in an Array

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?

Answer

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.