I'm new to ruby and I'm trying to make a loop that outputs a random number between 0 and 1 every second until user hits any key. Then, output the total number of random numbers generated and the average value of the numbers generated. However, I can't make the loop to stop at all, is there anything like break to stop the loop in ruby?
def random
ran = []
puts "Press 1 and 'enter' to start and 2 to stop \n"
s = gets.chomp
ran << Random.rand(0.0...1.1)
ran.each do|i|
ran << Random.rand(0.0...1.1)
puts i
sleep(1)
end
puts "The total number of random numbers generated is: #{ran.length}"
end
random
getsis a blocking function.sleep 1. You can not change the value of a variable from outside the loop, if this is what you mean.