(Ruby) Counting in Loops - ruby

could you help me out, please?
I want to write Ruby code in such a way that when I say the word "BYE!" 3 times in a row, it terminates the program.
My code is below
quotes = File.readlines('quotes.db')
puts = "What?"
print ">"
request = gets.chomp
while request != "BYE!"
puts quotes[rand(quotes.length)]
puts ">"
request = gets.chomp
end
Any I could amend the code to follow the rules I want?

Check if this is what you want. and tell me if any error occurs. this may be the rough code
quotes = File.readlines('quotes.db')
puts = "What?"
print ">"
counter = 0
request = gets.chomp
while counter < 3
counter += 1 if request.eqls?("BYE!")
puts quotes[rand(quotes.length)]
puts ">"
request = gets.chomp
end

puts 'If you type bye 3 times, this program will terminate'
bye_counter = 0
loop do
input = gets.chomp
if input == 'bye'
bye_counter += 1
else
bye_counter = 0
end
break if bye_counter == 3
end

I would do something like this:
quotes = File.readlines('quotes.db')
counter = 0
puts 'What?'
loop do
print '>'
request = gets.chomp
if request == 'BYE!'
counter += 1
break if counter >= 3
else
counter = 0
end
puts quotes.sample
end

Related

Stuck in while loop even though condition has been met

I'm writing this script to build a tic-tac-toe game. This is only the beginning (no turns yet). I want to let the user input again if the previous input is invalid.
def display_board(board)
first_row = " #{board[0]} | #{board[1]} | #{board[2]} "
second_row = " #{board[3]} | #{board[4]} | #{board[5]} "
third_row = " #{board[6]} | #{board[7]} | #{board[8]} "
row_divider = "-----------"
puts first_row
puts row_divider
puts second_row
puts row_divider
puts third_row
end
def valid_move?(board,index)
if (index >= 0) && (index <= board.length - 1) && (position_taken?(board,index) != FALSE)
return TRUE
else
return FALSE
end
end
def input_to_index(user_input)
index = user_input.to_i - 1
return index
end
def move(board, index, character = "X")
board[index] = character
end
def position_taken?(board,index)
if (board[index] == "X") || (board[index]=="O")
return FALSE
end
end
def turn(board)
puts "Please enter 1-9:"
user_input = gets.strip
index = input_to_index(user_input)
while valid_move?(board,index) == FALSE
puts "invalid"
turn(board)
end
move(board, index, character = "X")
display_board(board)
end
I am stuck on the while loop. If I input an invalid input and then a valid input, it runs through the while loop instead of ending the program. It should be true. The problem is fixed if I use an if statement instead of a while loop, but I want to learn to use while loops better.
Because you call "turn" (internal) from "turn" (external) and then the internal "turn" called is valid but the board and index on the external
"turn" didn't change.
try this:
def turn(board)
loop do
puts "Please enter 1-9:"
user_input = gets.strip
index = input_to_index(user_input)
if valid_move?(board,index) == TRUE
break
end
puts "invalid"
end
move(board, index, character = "X")
display_board(board)
end

Should this be refactored to be more DRY?

I am working through Chris Pine's Chapter 6 Deaf Grandman challenge. It looks very readable however I wonder if this is violating the DRY principle. If so, how can I refactor it?
puts "WHAT DID YOU SAY??"
said = gets.chomp
x = 0
bye_counter = 0
while bye_counter < 3
if said != said.upcase
puts "HUH?! SPEAK UP, SONNY!"
said = gets.chomp
bye_counter = 0
elsif said == said.upcase && said != "BYE"
puts "NO, NOT SINCE " + rand(1930..1950).to_s + "!"
bye_counter = 0
said = gets.chomp
elsif said == "BYE"
puts "HUH??"
bye_counter += 1
break if bye_counter == 3
said = gets.chomp
end
end
puts "OH.. OK!"
My solution:
message = "WHAT DID YOU SAY??"
bye_counter = 0
puts message
while bye_counter < 3
said = gets.chomp
if said == "BYE"
message = "HUH??"
bye_counter += 1
else
if said == said.upcase
message = "NO, NOT SINCE " + rand(1930..1950).to_s + "!"
else
message = "HUH?! SPEAK UP, SONNY!"
end
bye_counter = 0
end
break if bye_counter == 3
puts message
end
puts "OH.. OK!"

Ruby beginner: code only repeats 2 times

Hey the code I created only repeats 2 times.
After I type the second time "y" for the "continue_question"-method the code only stops.
def greeting
puts "Hello! Please type your name: "
name = gets.chomp.capitalize
puts "It is nice to meet you #{name}. I am a simple calculator application."
puts "I can add, subtract, multiply, and divide."
end
greeting
def calculator
puts "First number: "
#n1 = gets.chomp.to_i
puts "Secons number: "
#n2 = gets.chomp.to_i
def calculation
puts "Type 1 to add, 2 to subtract, 3 to multiply, or 4 to divide two numbers: "
operation_selection = gets.chomp.to_i
if operation_selection == 1
#result = #n1 + #n2
elsif operation_selection == 2
#result = #n1 - #n2
elsif operation_selection == 3
#result = #n1 * #n2
elsif operation_selection == 4
#result = #n1 / #n2
else
puts "Something went wrong!"
calculation
end
end
calculation
puts "Your Result is #{#result}"
end
calculator
def continue_question
puts "Do you want to continue? (y/n)"
continue = gets.chomp.to_s
if continue == "y"
calculator
elsif continue == "n"
puts "Bye!"
else
puts "What?"
continue_question
end
end
continue_question
Your code does not repeat 2 times, it repeats once.
The reason is because in your continue_question method, you do not tell it to repeat again:
def continue_question
puts "Do you want to continue? (y/n)"
continue = gets.chomp.to_s
if continue == "y"
calculator # <-- This causes it it repeat ONCE!
elsif continue == "n"
puts "Bye!"
else
puts "What?"
continue_question
end
end
A quick fix is to re-call the continue_question method below that line, to recursively repeat itself:
def continue_question
puts "Do you want to continue? (y/n)"
continue = gets.chomp.to_s
if continue == "y"
calculator
continue_question # <-- Add this to repeat indefinitely
elsif continue == "n"
puts "Bye!"
else
puts "What?"
continue_question
end
end
The problem is that continue_question only executes once, at the end of your code, but you need to loop until user exits (i.e types n).
So simply add a loop inside continue_question, for example:
def continue_question
continue = "y"
until continue == "n" do
puts "Do you want to continue? (y/n)"
continue = gets.chomp.to_s
if continue == "y"
calculator
elsif continue == "n"
puts "Bye!"
else
puts "What?"
end
end
end
Hey the code I created only repeats 2 times.
I think you misunderstand the following:
if continue == "y"
calculator
elsif continue == "n"
puts "Bye!"
When you call the above function calculator, you are still executing the continue_question function. So when the calculator finishes executing, continue_question will finish as well and the program will stop. For the wanted result you can try using a loop.

puts statement is printing on two lines

I have a class called PolynomialElements and inside that class I have a method called printElement that has a puts statement that print two variables. The puts statement is printing the variables on different lines. How do I get puts to print the two variables on one line. My code is below, it is line #5 where the puts statement is.
class PolynomialElements
attr_accessor :element, :size
def printElement
puts "#{element}x^#{size}"
end
end
askAgain = true
polyArray = Array.new
while askAgain
puts "How many numbers do you want to enter? "
numString = gets
num = numString.to_i
while num > 0
puts "Enter a value for the Polynomial "
value = gets
polyArray.push(value)
num -= 1
end
sizeOfArray = polyArray.length
polyArray.each do |x|
var = PolynomialElements.new
var.element = x
sizeOfArray -= 1
var.size = sizeOfArray
var.printElement
end
puts "Enter y to enter new number or anything else to quit"
cont = gets
if cont.chomp != "y"
askAgain = false
else
polyArray.clear
end
end
In the while loop change:
value = gets
to:
value = gets.chomp
You will then get:
Enter a value for the Polynomial
3
1x^2
2x^1
3x^0

How do i get it so the array keeps building not so it is replaced each time?

so here is what i want to do.
I am trying to accomplish so the letter variable gets added to the array each time it runs. The issue is, the variable letter keeps getting re written overtime the loop runs again. So if i type ā€œgā€ so the variable letter is ā€œgā€, it'll put that variable in the array then run it again and repeat there process. So after the loop run 5 times, i want the array to be [l,g,e,f,g]. But instead it gets replaced everytime so instead of array being [l,g,e,f,g], its just [g] cuz thats what the variable letter is currently.
def checkLetter(word)
x = 0
while x < 5 do
puts "Enter a letter"
letter = gets.chomp.to_s
if word.include?(letter) == true
puts "The letter is in it"
allLetters = []
allLetters << letter
end
if word.include?(letter) == false
puts "Try again"
#add body part
end
x = x + 1
end
puts allLetters.inspect
end
puts "enter a word"
word = gets.chomp
checkLetter(word)
You need to move allLetters = [] outside of your loop
def checkLetter(word)
x = 0
allLetters = [] # look here
while x < 5 do
puts "Enter a letter"
letter = gets.chomp.to_s
if word.include?(letter) == true
puts "The letter is in it"
allLetters << letter
end
if word.include?(letter) == false
puts "Try again"
#add body part
end
x = x + 1
end

Resources