degenPenguin
degenPenguin

Reputation: 725

In my Ruby Code, Why does my variable inside a string produce a new line?

Ok so this is my first day learning and I was trying to create a very basic questionnaire with Ruby.

For example, this would be my code:

print "What is your name? "
name = gets
puts "Hello #{name}, Welcome."

print "What year were you born in?"
year =  2014
year1 = gets.chomp.to_i
year2 = year-year1
puts "Ok. If you were born in #{year1}, then you are probably #{year2} years old."

Now if I input "Joe" for my name and "1989" for my birthdate, it would give me the following lines...

Hello Joe
, Welcome.

Ok. If you were born in 1989, then you are probably 25 years old.

I'm really confused about what's so different about the two strings.

Upvotes: 3

Views: 858

Answers (2)

user3720516
user3720516

Reputation:

When you call "gets" it actually appends the newline character "\n" to the end of the string by default. May I suggest adding the method "chomp" to the end of gets to remove the new line?

New answer:

print "What is your name? "
name = gets.chomp
puts "Hello #{name}, Welcome."

print "What year were you born in?"
year =  2014
year1 = gets.chomp.to_i
year2 = year-year1
puts "Ok. If you were born in #{year1}, then you are probably #{year2} years old."

Upvotes: 1

Jimmy
Jimmy

Reputation: 37081

You've got the right idea with the way you're processing the year that the user inputs. When they type "Joe" at the prompt, this results in the string value "Joe\n" getting assigned to the name variable. To strip newlines off the end of the string, use the chomp method. This would change the line to name = gets.chomp.

You might also want to explicitly convert the input to a string. If the user ends the input with control-D, gets will return nil instead of the empty string, and then you'll get a NoMethodError when you call chomp on it. The final code would be name = gets.to_s.chomp.

Upvotes: 3

Related Questions