Ruby Miscellaneous Expressions
In this tutorial we will learn about chaining assignments, defined operator and parallel assignments.
Ruby: Chaining assignments
Very Commonly, in a program you want to initialize a set of variables with a same value, typically 0.
However, you can do this like
a = 0
b = 0
c = 0
But, there is another way called chaining assignments
used by programmers.
a = b = c= 0
Now all the three variables have the same value.
You can see that the variables a, b & c has the same value 0.
Ruby:: defined
Operator
This is an interesting feature of ruby. Using this in an expression we can determine what type of identifier it is. We have defined the variable a. We can now use defined operator to identify what is a?
Since variable a is declared locally it returned as local-variable
. Likewise, it returned method
for printf and assignment
for the expression a = 1.
Ruby: Parallel Assignment
Consider the variable a contains 5 and b contains 10 and now we have to swap the values of the variables.
It is done by,
a = 5
b = 10
temp = a
a = b
b = temp
But there is an efficient way to do this called parallel assignment
. This can be done by a, b = b, a . Quiet simple. Right?
Initially the values of a and b is 5 and 10 and after parallel assignment, the values of a and b is swapped
.