The Crystal Programming Language Forum

Rand called once pr outer iteration instead of per iteration

pop = Array.new(3) { Array.new(2, rand(0.0..10.0)) }
puts pop

Prints e.g.
[[0.7382419246766038, 0.7382419246766038], [4.234956697837181, 4.234956697837181], [9.754968679116494, 9.754968679116494]]

I.e. each inner array contains the same random number instead of a different one.

Is this expected behavior?
Can I succinctly avoid this?

Yes, it’s expected. Do this:

Array.new(3) { Array.new(2) { rand(0.0..10.0) } }
1 Like

Nice really enjoy this language! Thanks a lot!