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


Why 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

Ok, 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:


Fixes it.


Anyway, if you have any useful insights or alternatives, please let me know!

John Steer-Fowler
John Steer-Fowler
Courses Plus Student 11,734 Points

You 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