Reputation: 21
I just started learning ruby. Can someone let me know why this is not running? Thank you.
greeting_preference = true
until greeting_preference
Puts "How should I greet you?"
greeting_preference = gets.chomp
if greeting_preference == "Bonjour!"
puts "Bonjour!"
greeting_preference = true
if greeting_preference == "Hola!"
puts "Hola!"
greeting_preference = true
if greeting_preference == "in Afrikaans"
puts "Hallo!"
greeting_preference = true
else
puts "Uh, hi?"
end
Upvotes: 0
Views: 88
Reputation: 133
You have to end the until statement.
The until statement Executes code while conditional is false, so until !greeting_preference
greeting_preference = false
until greeting_preference do
puts "How should I greet you?"
greeting_preference = gets.chomp
if greeting_preference == "Bonjour!"
puts "Bonjour!"
greeting_preference = true
elsif
greeting_preference == "Hola!"
puts "Hola!"
greeting_preference = true
elsif
greeting_preference == "in Afrikaans"
puts "Hallo!"
greeting_preference = true
else
puts "Uh, hi?"
end
end
Upvotes: 0
Reputation: 749
put enclosing end
with if-else
greeting_preference = true
while greeting_preference
puts "How should I greet you?"
greeting_preference = gets.chomp
if greeting_preference == "Bonjour!"
puts "Bonjour!"
greeting_preference = true
end
if greeting_preference == "Hola!"
puts "Hola!"
greeting_preference = true
end
if greeting_preference == "in Afrikaans"
puts "Hallo!"
greeting_preference = true
else
puts "Uh, hi?"
end
end
Better use case
statement :
greeting_preference = true
while greeting_preference
puts "How should I greet you?"
msg = gets.chomp
puts case msg
when "Bonjour!"
"Bonjour!"
when "Hola!"
"Hola!"
when "in Afrikaans"
"Hallo!"
else
greeting_preference = false
"Uh, hi?"
end
end
Upvotes: 2
Reputation: 54303
You can write FORTRAN in any language. :)
Your code would be easier with a Hash
. It's basically a dictionary in which you can define keys (greetings) and values (answers). If the key isn't found, ask again!
greetings = {
'Bonjour!' => 'Bonjour!',
'Hola!' => 'Hola!',
'in Afrikaans' => 'Hallo!'
}
puts 'How should I greet you?'
puts "(possible choices are #{greetings.keys})"
until greeting = greetings[gets.chomp]
puts 'Uh, hi?'
end
puts greeting
It outputs:
How should I greet you?
(possible choices are ["Bonjour!", "Hola!", "in Afrikaans"])
Hello?
Uh, hi?
Hi!
Uh, hi?
Hola!
Hola!
Upvotes: 1
Reputation: 30071
It looks like you just end
your until
. Your if
s and if-else
s need an end
as well
if greeting_preference == "Bonjour!"
puts "Bonjour!"
greeting_preference = true
end
if-else
if condition
puts "something"
else
puts "something else"
end
Upvotes: 3