Came across this little snippet today
$*[0] |
After a bit of digging, I found out it means almost the same as
ARGV[0] |
I say almost because, while I can’t find a practical difference, they are actually different types of objects.
[Desktop]$ irb 1.9.3-p125 :001 > defined? $* => "global-variable" 1.9.3-p125 :002 > defined? ARGV => "constant" |
As you can see, the first is a “global-variable” and the second a “constant”. But accessing either with the same index produces the same result.
So it’s a way of reading the first argument passed to a command line program. The simplest way to show this is to just throw this in a Ruby file and run is with a test paramater:
puts ARGV[0] puts $*[0] # ruby foo.rb this-is-a-test # this-is-a-test # this-is-a-test |
This got me wondering about the other global variables defined by the system. You can find them by running
ruby -r debug foo.rb |
At the prompt issue the ‘v g’ command. You’ll see a list of globals. Cool. Now, what do they mean? The ones I find the most useful are:
$0 # name of the Ruby program currently being run</li> $$ # process number of the current process</li> $! # Reference to the associated exception object</li> $@ # Backtrace for last raised exception</li> $_ # String last read by gets</li> $. # Last line number read</li> $~ # Match data for last regexp match</li> |
There’s a heap more, but these are the ones I think seem the most useful.

{ 0 comments… add one now }