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?
string[0] is a new string that contains the first character of string . It is, in fact, syntactic sugar for string. [](0) , i.e. calling the method String#[] on the String object stored in the variable string with argument 0 .
Its name is $_ (dollar underscore). Ruby has many global variables like this; there's a complete list of them here. But $_ is one of the most useful. Indeed, along with the globals relating to regular expressions, it's the only one I use with genuine regularity. There are five key places that $_ is used.
In ruby 'a ||= b' is called "or - equal" operator. It is a short way of saying if a has a boolean value of true(if it is neither false or nil) it has the value of a. If not it has the value of b.
The conversion value for 1 USD to 1.603 RBC.
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 $_
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With