I am trying to populate an array of four elements with positive integers that are less than 9.
Here is my code:
generated_number=Array.new(4)#create empty array of size 4
generated_number.each do |random| #for each position in the array create a random number
random=rand(10)
end
puts generated_number
I don't understand what I'm missing.
Since Math. random() returns random double value between 0 and 1 , we multiply it by 100 to get random numbers between 0 to 100 and then we cast it into type int . To store random double values in an array we don't need to cast the double value returned by Math. random() function.
Use Math. random() and Math. floor() method to get the random values. Push the values one by one in the array (But this approach may generate repeated values).
You can pass a range to rand()
Array.new(4) { rand(1...9) }
I think you're over complicating things.
generated_numbers = 4.times.map{Random.rand(8) } #=> [4, 2, 6, 8]
edit: For giggles I put together this function:
def rand_array(x, max)
x.times.map{ Random.rand(max) }
end
puts rand_array(5, 20) #=> [4, 13, 9, 19, 13]
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