Basic Ruby Programming - ruby

I have the following ruby code, from a learning to program book. I understand it ,however it asks me to try and remove the variable good_answer and answer. It says I will have to use return to exit the loop. I am not sure where to start. Any clues would be great, I just want to figure it out.
def ask question
good_answer = false
while (not good_answer)
puts question
reply = gets.chomp.downcase
if (reply == 'yes' or reply == 'no')
good_answer = true
if reply == 'yes'
answer = true
else
answer = false
end
else
puts 'Please answer "yes" or "no".'
end
end #while ends here
answer #This is what we return (true of false)
end
puts
ask('Do you like eating Cheese?')
ask('Are you crazy?')
rain = ask 'Do you like rain?'
puts rain

I would just do what it says - put return in where answer is being used:
def ask question
while (true)
puts question
reply = gets.chomp.downcase
if (reply == 'yes' or reply == 'no')
if reply == 'yes'
return true
else
return false
end
else
puts 'Please answer "yes" or "no".'
end
end #while ends here
end

Related

Ruby Endless Loop

I am new to Ruby. I have written the code below, its working about 90% except the else statement. The else statement triggers endless loop. I just want it to ask user to try again. Here is my code
puts "Do you want to print something? (Y / N)"
user = gets.chomp.downcase
answer = true
while answer
if user == "y"
puts "Something"
answer = false
elsif user == "n"
puts " "
answer = false
else
puts "Invalid input! Please enter Y or N"
end
end
Somewhat shorter (note user has gone, the answer is now referred to as answer).
answer = ""
until (answer == "y") or (answer == "n")
puts 'Do you want to print something? (Y/N)'
answer = gets.chomp.downcase
end
Once you exit the else, answer is still true. If you want to re-prompt, you can move your puts and user statement into the loop.
Something like this should work.
while true # (alternately) loop do
puts 'Do you want to print something? (Y/N)'
case gets.chomp.downcase
when 'y'
puts 'foo'
break
when 'n'
puts 'bar'
break
else
puts 'Invalid input! Please enter Y or N'
end
end
You can use break to exit out of your loop instead of setting up another variable. Also, this looks like a good use-case for a case statement to have some explicit cases listed.

Ruby trouble with breaking loop

All right, I have the programming aptitude of a goldfish, so I could use some help. I have the following code (please excuse my terrible sense of humor):
puts 'Do you have a middle name?'
answer=gets.chomp.downcase
while true
if answer != ('yes' || 'no')
puts 'Yes or no answers only, dumbass.'
puts 'So I\'ll ask again. Do you have a middle name?'
answer=gets.chomp.downcase
elsif answer == ('yes' || 'no')
if answer == 'yes'
puts 'Cool. What is it?'
middlename=gets.chomp
puts middlename +'? That\'s dumb.'
break
if answer == 'no'
puts 'I guess you aren\'t cool enough.'
break
end
end
end
end
puts 'Well, smell ya later.'
It works mostly fine, but I have one problem: choosing the no option. I cannot figure out how to get that to work. It will loop fine, and choosing the yes option works.
Basically, my question is: how do I create a loop with two break options?
For something like this you should use a case/when which is a Ruby switch statement because having all of those if/end blocks will get confusing fast.
Also please read this guide: https://github.com/bbatsov/ruby-style-guide
It will teach you how to properly format your ruby code.
puts 'Do you have a middle name?'
answer=gets.chomp.downcase
case answer
when 'yes'
puts 'Cool. What is it?'
middlename=gets.chomp
puts middlename +'? That\'s dumb.'
when 'no'
puts 'I guess you aren\'t cool enough.'
else
puts 'Yes or no answers only, dumbass.'
puts 'So I\'ll ask again. Do you have a middle name?'
answer=gets.chomp.downcase
end
puts 'Well, smell ya later.'
And if you always want it to loop when they don't answer yes or no. You can do that by wrapping the code block in a loop as follows:
puts 'Do you have a middle name?'
answer=gets.chomp.downcase
loop do
case answer
when 'yes'
puts 'Cool. What is it?'
middlename=gets.chomp
puts middlename +'? That\'s dumb.'
break
when 'no'
puts 'I guess you aren\'t cool enough.'
break
else
puts 'Yes or no answers only, dumbass.'
puts 'So I\'ll ask again. Do you have a middle name?'
answer=gets.chomp.downcase
end
end
puts 'Well, smell ya later.'
See this answer: How to write a switch statement in Ruby
if answer != ('yes' || 'no') isn't doing what you think it is. Since 'yes' is non-nil, which is true, the logical OR is short-circuited and the value of the parenthetic expression is always 'yes'. Try if answer != 'yes' && answer != 'no' instead.

Ruby "end" statement problems [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am stuck with a program that won't run properly. Here is my code:
puts '<Input greeting below>'
answer = gets.chomp
if answer == 'Hello' || 'Hi'
answer == true
else
answer == false
puts 'Hey, how are you?'
answer2 = gets.chomp
if answer2 == 'I\'m good' || 'I\'m doing well'
answer2 == true
else
answer2 == false
puts 'That\'s good. Would you like to know facts about ruby programming?'
answer3 = gets.chomp
if answer3 == 'Sure'
answer3 == true
else
answer3 == false
puts 'Ok, well did you know that {hello, world} was the first program ever made?'
answer4 = gets.chomp
if answer4 == 'Yes'
answer4 == true
else
answer4 == false
puts 'Wow, you\'re pretty good! Would you like to know another fact?'
answer5 = gets.chomp
if answer5 == 'Sure'
answer5 == true
else answer5 == false
puts 'Alright, did you know the programming language "Ruby"
was developed by a Japanese techonolgist named "Yukihiro Matsumoto"
because he wasn\'t satisfied with the other programming languages?'
end
end
end
end
end
Windows CMD says that I have a problem on line 29 with the "end" part. I can't figure it out. Can someone please help?
You've got a number of problems here that need to be fixed before you can get a working program.
First up, if x == A || B does not mean what you think it does. This evaluates to if x == (A || B) where it will only compare to the first string, not the second. To test against multiple possible matches the best approach is to use case:
case (answer)
when 'Hello', 'Hi'
# Matches!
else
# Not matched
end
You can also break out several different conditions by adding additional when clauses, and you can even use regular expressions to catch variations in case, and so forth.
As I added in a comment, this nested if pattern needs to go away. You need to switch to a state system instead:
state = :greeting
loop do
case (state)
when :greeting
puts "<input greeting below>"
case (gets.chomp)
when "Hello", "Hi"
state = :how_are_you
else
break
end
when :how_are_you
puts "Hey, how are you?"
case (gets.chomp)
when "I'm good", "I'm doing well"
state = :thats_good
else
break
end
# ... Additional `when` clauses.
end
end

What am I doing wrong in this Ruby code?

def pregunta
reply = gets.chomp.downcase
if reply == 'si'
puts 'Correcto'
end
if reply == 'no'
puts 'Incorrecto'
end
end
pregunta 'alfkjdasñlfj?'
After I ask a question ("pregunta" is question in english), the program should tell me if I'm right ("correcto") or wrong ("incorrecto") when I enter an answer ("si" or "no"). Instead of getting an answer, I get an "ArgumentError". What am I doing wrong?
I'm using Ruby 1.9.3-p194
pregunta doesn't take a parameter, but you pass one anyways. I might be wrong, but wasn't what you were trying to do something like this:
def pregunta(preg)
puts preg
reply = gets.chomp.downcase
if reply == 'si'
puts 'Correcto'
end
if reply == 'no'
puts 'Incorrecto'
end
end
You're not passing in a value to the function call, you're reading it from the terminal. Call the function and then enter in your string.
pregunta
si
Correcto
=> nil
You don't have any parameters in your method declaration.
You'll need something like this:
def pregunta(foo)
if foo == 'bar'
true
end
end
You are calling pregunta 'alfkjdasñlfj?' but that method has no arguments.
def pregunta(answer)
reply = answer.chomp.downcase
if reply == 'si'
puts 'Correcto'
end
if reply == 'no'
puts 'Incorrecto'
end
end
pregunta gets
maybe ?

ruby program basic design explanation

I want to rewrite the following code with the code below, but I am stuck.
def ask question
good_answer = false
while (not good_answer)
puts question
reply = gets.chomp.downcase
if (reply == 'yes' or reply =='no')
good_answer = true
if reply == 'yes'
answer = true
else
answer = false
end
else
puts 'Please answer "yes" or "no"'
end
end
answer
end
Replacement code:
def ask question
puts question
reply = gets.chomp
if (reply == 'yes' or reply == 'no')
puts reply.capitalize
else
puts 'Please enter "yes" or "no"'
#jump the code to like 2 ( but how?)- use while reply != empty & comment the below lines
puts question
reply = gets.chomp
end
end
I want to jump to the main part of program is there any goto, jump or can I call method inside that method?
I want to jump to the main part of program is there any goto, jump or can I call method inside that method?
Yes, it is called a loop, i.e., what you are using in your original code. Why in the world would you want to replace a loop with a goto? Makes no sense.
It can however be simplified. I don't like the checking against 'yes' or 'no', but I also don't have time to restructure your program.
def ask question
while true
puts(question)
reply = gets.chomp.downcase
if reply == 'yes' || reply == 'no'
return reply == 'yes'
else
puts('Please answer "yes" or "no"')
end
end
end
Even if there was a goto statement you shouldn't be using it. Not only is it bad form, but it causes all kinds of headaches for maintainers since your program ends up being hard to follow.
A better approach is to define proper structures for your questions and valid answers, then iterate over those simply, collecting the results into a structure you can use later:
# Auto-flush output buffer
STDOUT.sync = true
questions = [
[ 'Is this a good question?', 'yes', 'no' ],
[ 'Is the sky blue?', 'yes', 'no' ],
[ 'Do hamsters fly?', 'no', 'yes' ]
]
answers_given = [ ]
questions.each do |question, *answers|
print question + ' '
while (true)
answer = gets
answer.chomp!
if (answers.include?(answer))
puts "Thanks!"
answers_given << (answer == answers.first)
break
end
puts "You must answer one of #{answers.join(', ')}!"
print question + ' '
end
end
questions.each_with_index do |(question, *answers), i|
puts "#{question} #{answers_given[i]}"
end
You can try something liek this:
def ask_question
puts('Please answer "yes" or "no"') until (reply = gets.chomp.downcase) =~ /^(yes|no)$/
return reply == 'yes'
end
def ask question
puts question
reply = gets.chomp.downcase
if (reply == 'yes' or reply == 'no')
puts reply.capitalize
else
puts 'Please enter "yes" or "no"'
ask question # this does the looping of loop
end
end
Thanks, and sorry I didn't copy it well from my clipboard last time.

Resources