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?
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.
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.
There are different types of variables in Ruby: Local variables. Instance variables. Class variables.
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.
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
, andc
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 = ( )
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