Ruby Parallel Assignment
Parallel Assignment
Ruby supports the parallel assignment of variables which can be done in a single operation. Therefore you can declare several variables to the left as an assignment operator and several values to the right. The order of the values to the right must be same to the variables on the left. See the following syntax :
l1, l2, l3 = "Python", "Ruby", "PHP"
The assignment also swap the values of variables :
irb(main):038:0> n1 = 100
=> 100
irb(main):039:0> n2 = 200
=> 200
irb(main):040:0> n1, n2 = n2, n1
=> [200, 100]
It is also possible to make multiple assignments from the values returned by a method. Here is an example :
def add_values( x, y, z )
x = x/2
y = y/3
z = z/4
return x, y, z
end
puts(add_values(10, 20 , 30))
Output:
5 6 7
Previous:
Ruby Assignment Operators
Next:
Ruby Bitwise Operators
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework