In my Ruby code, why is my variable inside a string creating a newline?

Ok, so this is my first day of training and I was trying to create a very simple 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 enter "Joe" for my name and "1989" for my date of birth, it would give me the following lines ...

Hi Joe
, Welcome.

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

I am really confused about being so different from two lines.

+3


source to share


2 answers


You have the right idea for how you handle the year the user enters. When they type "Joe" at the prompt, it causes the string value "Joe \ n" to be assigned a variable name

. To output the lines of a string from the end of a string, use the chomp

. This will change the line to name = gets.chomp

.



You can also explicitly convert the input to a string. If the user completes the input with the -D control gets

will return nil

an empty string instead, and then you get NoMethodError

when you call chomp

on it. The final code will be name = gets.to_s.chomp

.

+3


source


When you call get, it actually adds the newline character "\ n" to the end of the line by default. May I suggest adding a "chomp" method to the end to remove the newline?

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."

      

+1


source







All Articles