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

Andrew Stelmach
12,583 PointsWhy can't I use a variable that has been defined through 'gets' inside this method?
So, I found out that, in Ruby, to define a global variable, you have to use '$', but I don't understand why THIS works:
$a=Time.new.year yearofbirth=1979
def calculateage(b) $a-b end
puts calculateage(yearofbirth)
Returns "35", But THIS doesn't:
$a=Time.new.year yearofbirth=gets
def calculateage(b) $a-b end
puts calculateage(yearofbirth)
(When you run it, it asks you to put in the number eg 1979, but it comes back with an error: String can't be coerced into Fixnum (TypeError).
1 Answer

Andrew Stelmach
12,583 PointsOk, after bloody AGES of digging I found out that yearofbirth, even though you enter a number, it's defined as a string so can only be used as such. You can use .to_i to convert it to an integer. So:
yearofbirth=gets.to_i
Fixes it.
Christ.
Anyway, if you have any useful insights or alternatives, please let me know!
John Steer-Fowler
Courses Plus Student 11,734 PointsJohn Steer-Fowler
Courses Plus Student 11,734 PointsYou answered your own question :D
You are using 'gets' which is actually (get string). Therefore, like you said, you can use the 'to.i' method to convert the string into an integer.
Keep up the good work