Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby variable assignment

Can someone explain this behavior:

a = b = c = 1, 2, 3 
a # => [1, 2, 3]
b # => 1
c # => 1

In the assignment a = b = c = 1, 2, 3, the variables a, b, and c should be assigned [1, 2, 3]. Any idea?

like image 908
Sachin Prasad Avatar asked Jul 02 '15 10:07

Sachin Prasad


People also ask

How do you assign a value in Ruby?

In Ruby assignment operator is done using the equal operator "=". This is applicable both for variables and objects, as strings, floats, and integers are actually objects in Ruby, you're always assigning objects.

What is an assignment variable?

Variable Assignment To "assign" a variable means to symbolically associate a specific piece of information with a name. Any operations that are applied to this "name" (or variable) must hold true for any possible values.

Does Ruby have variables?

There are different types of variables in Ruby: Local variables. Instance variables. Class variables.

What is an instance variable Ruby?

What's an instance variable? In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol. Example: @fruit. An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data.


1 Answers

Can someone explain why is this happening

@shivam already answered the question, but adding some parentheses might clarify things even more.

a = b = c = 1, 2, 3

is interpreted as:

a = [(b = (c = 1)), 2, 3]

The expression is evaluated in this order:

           c = 1
      b = (     )
a = [(           ), 2, 3]

the variables a, b, and c should be assigned [1, 2, 3]

To get the expected result, you could write:

a = b = c = [1, 2, 3]

which is interpreted as:

a = (b = (c = [1, 2, 3]))

and evaluated in this order:

          c = [1, 2, 3]
     b = (             )
a = (                   )
like image 182
Stefan Avatar answered Nov 16 '22 03:11

Stefan