nullnullnull nullnullnull - 1 year ago 61
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 Source


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download