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 trial

Ruby Ruby Basics (Retired) Ruby Numbers Practicing with Numbers

Year + future not adding

My year and future variables are not adding together

print "What year is it: " year=gets print " Enter future years : " future=gets name="Aaron" string="My name is #{name}" puts string puts "the year is #{year}" puts "In #{future} years it will be #{year + future}"

Why is this happening

this is what console spits out

What year is it: 2015
Enter future years : 20
My name is Aaron
the year is 2015
In 20
years it will be 2015
20

1 Answer

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

Hi, Aaron Endsley

There're couple of problems here.

  1. You noticed that the program's output broke into more numbers of lines than it needs to be? That's because the use of gets to accept user's input would always insert a newline character at the end, this is an undesirable side-effect. gets.chomp is better suited for such case, as it removed the tailing newline character.
  2. Now to answer the question you asked why year + future not working?. That's because these 2 variables were assigned by user's input; it's important to remember that, even though you might think you have entered a number, the result of get or get.chomp always stored in the variable as String, in the case of your code, they are "2015" and "20". By performing addition operation on 2 Strings, Ruby would just combine them together into one big String. To get the true mathematical addition, you may first convert these 2 variable into integer using the to_i method.
print "What year is it: "
year=gets.chomp               # use get.chomp here instead of gets
print "Enter future years : "
future=gets.chomp             # use get.chomp here instead of gets
name="Aaron"
string="My name is #{name}"
puts string
puts "the year is #{year}"
puts "In #{future} years it will be #{year.to_i + future.to_i}"


#=> What year is it: 2015
#=> Enter future years : 20
#=> My name is Aaron
#=> the year is 2015
#=> In 20 years it will be 2035

Hope it helps