Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialleonvsthings
12,236 PointsBasic birth year calculation
I've completed the numbers & methods parts in Ruby and wanted to calculate user's birth year with the things I've learned.
Came up with something like this:
print "How old are you? "
age = gets.chomp #if I don't add chomps the number gets /n and it's not recognized.
print "And what year are we in? "
year = gets.chomp
birthyear = year - age
print "That means you were born in #{birthyear}"
When I run this, I get:
hello.rb:11:in `<main>': undefined method `-' for "2016":String (NoMethodError) Did you mean? -@
What am I doing wrong?
1 Answer
Seth Kroger
56,413 PointsThere is difference between text and numbers in programming. When you read the input from the console with gets, it's always a text string (the 's' in gets). It still need to be converted into a number that the computer can understand as a number. For an integer (whole number) that is done with to_i in ruby.
print "How old are you? "
age = gets.chomp.to_i # changes the string to an integer number.
print "And what year are we in? "
year = gets.chomp.to_i
birthyear = year - age
print "That means you were born in #{birthyear}"
leonvsthings
12,236 Pointsleonvsthings
12,236 PointsThanks, that makes sense! I'll play around with the code and I just realized that I don't know how to properly use new line if it's coming after a string like #{birthyear}/n. Jason mentions that he'll show it later on but I haven't made it that far yet.