Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 575
degenPenguin Avatar asked Jan 17 '26 03:01

degenPenguin


1 Answers

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.

like image 129
Jimmy Avatar answered Jan 19 '26 17:01

Jimmy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!