Call the function several times and get a list of results

I want to call the function f 5 times (for example) 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 does not accept input and returns true or false . Therefore, when this is done, I get a list of 5 true / false values.

Is there a better way to do this using other built-in functions (maybe reduce ? I had this idea, but I can't figure out how to use it ...)

+6
source share
4 answers
 5.times.collect { f } 

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

I also prefer a longer 5.times instead of (1..5) . It also seems more communicative: I don't really β€œrepeat in range,” I β€œdo something five times.”

The IMO answer is slightly counterintuitive in this case, since I do not execute collect five times, but collect.5.times { f } does not work, so we still play a mental game.

+31
source

Try the block form of the Array constructor if you want to increment the arguments with zero base:

 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] 
+4
source

Use Array.new with a block

 Array.new(10) { f } 

The index value is available if you want:

 Array.new(10) { |i| f(i) } 

From the docs :

[With block] creates an array of a given size. Each element in this array is created by passing the index of the element to the given block and storing the return value.

This was possible, since at least 1.8.7 .

+1
source

You can simply shorten the code without putting to_a ... (1..5) enumerated, so that it works with the map.

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

0
source

Source: https://habr.com/ru/post/905551/


All Articles