Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby

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:

yearofbirth=gets.to_i

Fixes it.

Christ.

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