Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is $_[0] ,$_[1] in Ruby?

Tags:

ruby

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?

like image 834
Dude Avatar asked Dec 04 '12 09:12

Dude


People also ask

What does 0 mean in Ruby?

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 .

What is $_ in Ruby?

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.

What does ||= mean in Ruby?

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.

What is $1 in Ruby?

The conversion value for 1 USD to 1.603 RBC.


1 Answers

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          $_
like image 90
Sergio Tulentsev Avatar answered Nov 03 '22 14:11

Sergio Tulentsev