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
Scooter D
9,611 PointsQuestion about Ruby Code
I am learning Ruby code. First I started with the Ruby on Rails project on teamtreehouse, my friend had a book I am now learning the basics of Ruby from. I am doing example problems and have a question:
Code:
puts 'What\'s your favorite number?'
number = gets.chomp.to_i
number_new = number + 1
puts 'That\'s okay, I guess, but isn\'t ' + number_new.to_s + ' just a bit better?'
My question is why I have to use .to_i and the .to_s ?
Any help would be greatly appreciated, thanks!
2 Answers
Jason Seifer
Treehouse Guest TeacherIf you use the .to_i method, it converts what you type in as a string in to an integer. That lets you add the number to it :)
Justin Mullis
1,440 PointsThe to_s and to_i are methods on the number and string variables you've set, In the first and second lines the number entered from the prompt is interpreted as a string so to_i is needed to convert it to an integer. This is so you can add 1 to it in the third line. The fourth line could actually be written differently so you didn't have to convert it back to a string.
puts "That\'s okay, I guess, but isn\'t #{number_new} just a bit better?"
In your case you need to convert back to string because otherwise Ruby thinks you're trying to add a number and a string together, which obviously doesn't work :)