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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With