ruby how to stop a loop with user input? - ruby

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

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

Related

Restarting a loop from the top

I have the following:
text_counter = 0
MAXTEXT_COUNTER = 10
puts "hello, this will start"
loop do
puts "hello"
text_counter += 1
sleep(2)
if text_counter >= MAXTEXT_COUNTER
break
end
end
sleep(7200)
print "ended test"
Once the break has happened, how can I get it to start again from the top?
I'm now thinking I could nest this loop in an until loop with the condition of text_counter == 1000. This would break, then sleep for 2 hours, then start again until it hits 1000.
It looks like you need a loop within a loop where you repeat one N times, the other M times:
MAXTEXT_COUNTER = 10
puts "hello, this will start"
loop do
MAXTEXT_COUNTER.times do
puts "hello"
sleep(2)
end
print "ended test"
sleep(7200)
end
The outer loop is perpetual. The inner one runs a certain number of times and stops using the times method.
You're looking for next
It functions similarly to break, but returns control back to the top of the loop. It's great for creating flat control flow.
For example
0.upto(100) do |i|
if i % 7 == 0
puts "#{i} is a multiple of 7"
next
end
puts i
end
There is a retry keyword which repeats the loop from top, just what you've asked.
Or you can wrap your loop into a method and continuously call that method.

How do I display the largest number in an array in Ruby? [duplicate]

This question already has answers here:
How to find a min/max with Ruby
(5 answers)
Closed 4 years ago.
I have a homework assignment that I need to finish. I think most of the code is working but I am having trouble with the last part. I need to display the largest number that a user enters (into an array). Below is the code I have so far. I am open to any suggestions. Thanks in advance.
Here's the description of the assignment:
Write a Ruby application that allows a user to input a series of 10 integers and determines and prints the largest integer. Your program should use at least the following three variables:
a) counter: A counter to count to 10 (i.e., to keep track of how many numbers have been input and to determine when all 10 numbers have been processed).
b) number: The integer most recently input by the user.
c) largest: The largest number found so far.
class Screen
def cls
puts ("\n")
puts "\a"
end
def pause
STDIN.gets
end
end
class Script
def display_instructions
Console_Screen.cls
print "This script will take the user input of 10 integers and then
will
print the largest."
print "\n\nPress enter to continue."
Console_Screen.cls
Console_Screen.pause
end
def getNumber #accepts user input
list = Array.new
10.times do
Console_Screen.cls
print "This script accepts 10 integers."
print "\n\nPlease type an integer and press enter."
input = STDIN.gets
input.chop!
list.push(input)
end
end
def display_largest(number) #displays the largest integer entered by the
user
Console_Screen.cls
print "The largest integer is " +
end
def runScript
number = getNumber
Console_Screen.cls
display_largest(number)
end
end
#Main Script Logic
Console_Screen = Screen.new
LargestNum = Script.new
answer = ""
loop do
Console_Screen.cls
print "Are you ready to start the script? (y/n): "
print "\n\nWould you like instructions on how this script works? (h): "
answer = STDIN.gets
answer.chop!
break if answer =~ /y|n|h/i
end
if answer == "h" or answer == "H"
LargestNum.display_instructions
print "Are you ready to start the script? (y/n): "
answer = STDIN.gets
answer.chop!
end
if answer == "n" or answer == "N"
Console_Screen.cls
puts "Okay, maybe another time.\n\n"
Console_Screen.pause
else
loop do
LargestNum.runScript
print "\n\nEnter Q to quit or press any key to run the script again: "
runAgain = STDIN.gets
runAgain.chop!
break if runAgain =~ /Q/i
end
end
This question has been asked and answered so many times before. Personally I think, as this answer suggests, the built in .max is the best solution.
[1, 3, 5].max #=> 5
Have you learned about for loops yet? You have to iterate through the array. For a very trivial example, you can do something like
max = 0
for element in list
if element > max
max= element
return max

Generate largest number of 10 inputs

New to scripting here. Basically, I am needing to write a program to accept 10 input numbers and return the largest in the list.
I have this code, but obviously it is not running:
class Generator
def getNumbers
number = Array.new
puts "To begin, You will need to enter your numbers."
print "Press Enter to continue."
Console_Screen.pause
10.times do
print "\nPlease enter any number: "
input = STDIN.gets
input.chop!
list.push
return list
end
list.push(number)
print list.max
end
end
Console_Screen.new
Find = Generator.new
end
Can anyone help me with what I coded incorrectly?
There are many problems with your code. Among them I may point:
1) You created an array named number to store your numbers and then tried to push them to another variable named list;
2) As #tadman pointed, you used a return inside a times block and this makes the block to be executed only once;
3) You never invoked getNumbers to make your process really happen!
This code would do what you need:
class Generator
def get_numbers
numbers = Array.new
puts "To begin, You will need to enter your numbers."
puts
10.times do
print "\nPlease enter any number: "
input = STDIN.gets
input.chop!
numbers.push(input.to_i)
end
print numbers.max
end
end
Find = Generator.new
Find.get_numbers
Notice that I changed the name of your method from getNumbers to get_numbers, which is much more Ruby-like.
Notice that I also changed the name of your array from number to numbers, 'cause it will store numbers, not a single number. Naming your varables correctly may help you to think correctly about your problem. It also helps when it comes for other people reading your program. Even you, six months later, will have problems to understand your own code if you don't name things correctly an comment you code well.
By the way, I also pushed the numbers to numbers as integer, using #to_i. This will make the numbers be compared as numbers, not as strings. If you researsh a bit you'll find out this could be a bit different. If someone enters 0300 as a number, it will be considered to be smaller then 200 as string, but when converted to integers, they will be in the correct order.
Consider this approach perhaps:
#script.rb
nums = []
10.times do |c|
puts "enter number #{c+1}"
nums << gets.to_i
end
puts "max number is #{nums.max}"
Example
$ ruby script.rb
enter number 1
#5
enter number 2
#3
enter number 3
#66
enter number 4
#4
enter number 5
#3
enter number 6
#2
enter number 7
#1
enter number 8
#6
enter number 9
#9
enter number 10
#0
#max number is 66
I had the same assignment and this is what I ended up creating. (I had to get a little more involved with input control and I'm sure there's easier ways of doing this. Also had to utilize the variables as part of the grade. I assume to prevent me from ripping off the code above.)
class Screen
def cls
puts ("\n" * 25)
puts "\a"
end
def pause
STDIN.gets
end
end
Console_Screen = Screen.new
num = [] #array to store user input
$counter = 1
loop do
puts "Please enter number " + $counter.to_s + " of a series of 10 numbers in order to determine the largest."
# Console_Screen.pause
loop do
print "Enter Number Here:"
number = gets.chomp
num << number.to_i if number =~ /[0-9]/ #only writes to the array if it's a number
break if number =~ /[0-9]/ #only allow numbers
end
$counter += 1
break if $counter == 11
end
puts "Press Enter to have your numbers sorted and the largest presented to you."
Console_Screen.pause
largest = num.max
puts "This is your largest number: " + largest.to_s
Console_Screen.pause

Ruby script need fix

I'm having a problem with my ruby script. If anyone could help, I'd really appreciate it. The problem is that the number is stuck between 1-2; where 2 is too high and 1 is too low. The guesses should be integers only.
#!/usr/bin/ruby
def highLow(max)
again = "yes"
while again == "yes"
puts "Welcome to the High Low game"
playGame(max)
print "Would you like to play again? (yes/no): "
again = STDIN.gets.chomp
if again == 'no'
puts "Have a nice day, Goodbye"
end
end
end
#This method contains the logic for a single game and call the feedback method.
def playGame(max)
puts "The game gets played now"
puts "I am thinking of a number between 1 and #{max}." #It show what chosen by user
randomNumber = rand(max)+ 1
print "Make your guess: "
guess = STDIN.gets.chomp
feedback(guess, randomNumber)
end
#Start while loop
#Logic for feedback method. It's ganna check the guess if it's high or low.
def feedback(guess, randomNumber)
count = 1
while guess.to_i != randomNumber
count = count + 1
if guess.to_i < randomNumber
print "That's too low. Guess again: "
else
print "That's too high. Guess again: "
end
guess = STDIN.gets.chomp
end
puts "Correct! You guessed the answer in #{count} tries!"
end
highLow(ARGV[0])
Change your last line to this:
highLow(ARGV[0].to_i)
The ARGV array contains all the passed in arguments as strings, so you have to cast it to integer.

Take a number input, iterate up to the top of a given range and output numbers into a file

I'm hoping to get my Ruby script to start at an inputted number, say 100, and itterate all the way up to the end of the range; 1000. Having all the numbers in between saved to a file.
This is a code I have so far:
#!/usr/bin/env ruby
if ARGV.length ==0;
puts "Enter the start number"
else puts ARGV.size
ARGV.each do |a|
for i in 0..1000 do
puts i;
end
end
end
To run it I'm typing:
ruby increment.rb 100 > increment.txt
However, it ignores the input number and starts at 1 regardless.
What am I doing wrong?
It starts at 0 because you're giving it the range 0..1000, which starts at 0. If you want to use the numeric value of a as the starting point, use a.to_i instead of 0.
ARGV is an array and the first argument is stored in ARGV[0] second in ARGV[1] etc
if ARGV[0]
start = ARGV[0].to_i
else
puts "Enter the start number"
start = gets.to_i
end
(start .. 1000).each do |i|
puts i
end

Resources