Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function multiple times and get a list of results

I want to call the function f 5 times (for instance) and get a list of results. Right now I have this:

(1..5).to_a.map!{f}

Note: Right now f is a function that takes no input and returns true or false. So when this is done running, I get a list of 5 true/false values.

Is there a better way to do this using other built in functions (possibly reduce? I had that idea but cannot figure out how to use it...)

like image 649
trh178 Avatar asked Jan 09 '12 19:01

trh178


2 Answers

5.times.collect { f }

(Assuming no parameters. map is an alias to collect; I prefer the name collect when actually collecting as it seems more communicative, but YMMV.)

I also prefer the longer 5.times instead of (1..5). This seems more communicative: I'm not really "iterating over a range", I'm "doing something five times".

IMO the answer is slightly counter-intuitive in this case, since I'm not really running collect five times, but collect.5.times { f } doesn't work, so we play a bit of a mental game anyway.

like image 132
Dave Newton Avatar answered Nov 14 '22 04:11

Dave Newton


Try the block form of the Array constructor if you want zero based increasing arguments:

Array.new(5) {|x| (x+1).to_f} # => [1.0, 2.0, 3.0, 4.0, 5.0]
Array.new(10) { rand } # => [0.794129655156092, ..., 0.794129655156092]
like image 39
maerics Avatar answered Nov 14 '22 05:11

maerics