0

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
3
  • 2
    gets is a blocking function. Commented May 14, 2018 at 19:27
  • You need to ask the user for an input inside the loop, then break if a condition is met. For example instead of sleep 1. You can not change the value of a variable from outside the loop, if this is what you mean. Commented May 14, 2018 at 20:13
  • Please don't edit solutions into your questions. If you think you've found the answer, post it below as an answer and mark it "accepted" with the green checkmark by the voting buttons. Commented May 14, 2018 at 21:02

1 Answer 1

1

You don't really need another thread.

numbers = []

puts 'Press ENTER to start'
puts 'Press Ctrl-C to stop'
gets

loop do
  numbers << rand
  sleep 1
rescue Interrupt
  puts
  printf "Count: %d\n", numbers.size
  printf "Mean: %f\n", numbers.sum / numbers.size

  exit
end

Requires Ruby >= 2.5

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.