More Irb Tips

I was talking to someone (can't remember who) at Rubyconf and they brought up #local_variable. This method shows you the names of all the local variables in scope.

Funny, I don't remember this function, and if I did know it, I had forgotten about it. So, I fired up irb and type it in to see what I get back:

local_variables   #=> ["_"]
x = 5             #=> 5
local_variables   #=> ["_", "x"]

Hmmm, this is interesting. I know there is a variable in irb that contains the value of the last expression, but it is not easy to remember. But, it looks like _ will do the same thing.

I'm always doing math expressions where I need the value of the previous expression. So now, instead of up-arrow and add to the equation, I can use _.

5/7.0    #=> 0.714285714285714
2*_      #=> 1.42857142857143

Of course, you can you this for any irb expression, and best of all, it is a variable name I can actually remember. :)

About this Post

Author:
Jim
Published:
2006-10-20 14:23
Updated:
2006-10-20 22:07
Sections:
Ruby