0

Could someone tell me why this Ruby on Rails solution I came up with is returning the IF statement's output regardless of what'a written in the console? (if you answer the question asked with "in Spanish" you still get a "Bonjour!" in return...

Assignment 2: Global Greetings

Ask the user how they would like to be greeted.

If they say "in French", respond with "Bonjour!"

If they say "in Spanish", respond with "Hola!"

If they say "in Afrikaans", respond with "Hallo!"

Handle all other input with "Uh, hi?"

puts "How would you like to be greated?"
greet = gets.chomp

if greet = "in French"
    puts "Bonjour!"
elsif greet = "in Spanish"
    puts "Hola!"
elsif greet = "in Afrikaans"
    puts "Hallo!"
else
    puts "Uh, hi?"
end
1
  • you're using single equals instead of double equals. Change if greet = to if greet == Commented Aug 14, 2016 at 21:04

2 Answers 2

5

With = you make an assignment.

You need a == like here:

puts "How would you like to be greated?"
greet = gets.chomp

if greet == "in French"
    puts "Bonjour!"
elsif greet == "in Spanish"
    puts "Hola!"
elsif greet == "in Afrikaans"
    puts "Hallo!"
else
    puts "Uh, hi?"
end

You can also use a case statement:

puts "How would you like to be greated?"
greet = gets.chomp

case greet 
when "in French"
    puts "Bonjour!"
when "in Spanish"
    puts "Hola!"
when "in Afrikaans"
    puts "Hallo!"
else
    puts "Uh, hi?"
end

If you use it in combination with a regular expression, you may also catch different spellings or sentences:

puts "How would you like to be greated?"
greet = gets.chomp

case greet 
when /French/i
    puts "Bonjour!"
when /Spanish/i
    puts "Hola!"
when /Afrikaans/i
    puts "Hallo!"
else
    puts "Uh, hi?"
end
Sign up to request clarification or add additional context in comments.

3 Comments

The real solution is the case statement version. Not sure why you're indenting the first when, though. case/when/end should all be at the same indentation level according to virtually every Ruby style guide. One thing that would simplify the expressions here is case greet.downcase to avoid having to make each case-sensitive.
@tadman the first indention was just by accident when I recoded the if/elsif-version. I adapted it. My regular exceptions are defined case insensitive (option i in the regexp). The case greet.downcase would make it more obvious.
Yeah, I mean you can downcase once or put in /i many times. Doing the thing once is usually more concise.
0

= is an assignment operator and == is used for comparison

if "in French" == "in French"  // returns true
    puts "Bonjour"
else
    puts "Uh, hi?"

value = 10 // assign 10 to the variable value
puts value //print 10

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.