6

I am a Java developer, and I have been given Ruby code to understand and later to work on.

I went through the Ruby tutorials on tutorialspoint.com but I can't figure out what $_[0] is.

It is being assigned to a variable in the code, and it is definitely not a command-line argument because I wrote code to test that and it failed. So, can anyone say what the significance of it is?

| |
  • While Ruby supports many "magic" variables, the use of them is controversial, and, as you see, somewhat of a maintenance issue because they are obscure. I'd recommend looking at the English module for more readable names of the variables. – the Tin Man Dec 4 '12 at 12:39
15

It's one of the magic variables.

$_ holds value of the last line read from standard input. $_[0] is, therefore, first symbol of that string.

See English.rb for more magic variables

# The last line read by <tt>Kernel.gets</tt> or
# <tt>Kernel.readline</tt>. Many string-related functions in the
# +Kernel+ module operate on <tt>$_</tt> by default. The variable is
# local to the current scope. Thread local.
alias $LAST_READ_LINE          $_
| |
  • 3
    Although it's a magic variable it's not actually global. The $ is misleading. – Andrew Haines Dec 4 '12 at 10:37
  • 1
    Yepp, most of the "magic globals" are actually "magic thread-locals". – Jörg W Mittag Dec 4 '12 at 17:30
5

$_ - string last read by gets

[0] is of course, indexing into that string.

http://www.rubyist.net/~slagell/ruby/globalvars.html

| |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.