1

I'm super beginner to ruby, but for some reason my if statement isn't working. Whenever the name 'Cristina' is entered, the program continues to print "Hello there".

def Cus_free_makers_eg1heChallenge(str)
  str = gets
  if str == "Cristina"
    print "Hello Cristina!"
  else
    print "Hello there!"
  end
  return str
end 
1
  • Change it to if str == "Christina\n". After the gets, the string will have a terminating newline. More sensible would be maybe a if /Christina/ =~ str. Commented Mar 25, 2021 at 9:42

2 Answers 2

1

Add strip to remove newline:

str = gets.strip
if str == "Cristina" 
  print "Hello Cristina!"
else
  print "Hello there!"
end
Sign up to request clarification or add additional context in comments.

2 Comments

Still doesn't seem to work. I added an elsif statement also, but that doesn't work either..
This does work. I think chomp is the preferred way - but both work in this case.
1

This works:

str = gets.chomp

if str == "Cristina"
  print "Hello Christina!"
else
  print "Hello there!"
end

str

Ruby gets statement is usually ended with chomp or chomp! to -- you guessed it -- "chomp" aka remove the trailing newline and carriage characters. More info in Ruby doc: https://docs.ruby-lang.org/en/3.0.0/String.html#method-i-chomp

I also took the opportunity to remove return and also the trailing end as both aren't necessary.

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.