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...)
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With