Call a function multiple times and get a list of results
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.
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]
You could just shorten your code by not putting to_a
... (1..5) is an enumerable so it works with map.
(1..5).map!{f}