Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

ruby

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?

like image 631
nullnullnull Avatar asked Nov 19 '25 01:11

nullnullnull


2 Answers

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.

like image 67
Serabe Avatar answered Nov 21 '25 13:11

Serabe


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.

like image 33
Daniel Evans Avatar answered Nov 21 '25 15:11

Daniel Evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!