This blog post discusses the support for Rightward assignments in ruby.
Before
Historically, all of the early programming languages were designed by Mathematicians. It’s a common practice in mathematics to say let x = 4y + z
, which is read as let x
be equal to 4y + z
.
So the same pattern is followed in programming languages as well.
For assigning a value to a variable, we typically do age = 42
in ruby. Here we are assigning the Rvalue
42
to an Lvalue
age
.
While the above pattern has become standardized, it feels somewhat unnatural as we read most of the spoken languages from left to right.
We were not able to do something like 42 => age
.
After
With the recent changes, Ruby supports the Right ward assignments as demonstrated below.
3 => box_height # This is equivalent to box_height = 3
Let’s take a look at few more examples:
Example 1
[170, 65] => height, weight
which is equivalent to
height, weight = [170, 65]
Example 2
def traits
[170, 65]
end
traits => height, weight
which is equivalent to
height, weight = traits
Additional notes:
There are already some languages which support rightward assignment.
TI-BASIC’s
uses STO (“store”) operation to achieve this, as demonstrated below:
42→age
R language
also has a similar way of doing this 42 -> age
.
Note: This is added as an experimental feature in Ruby, which means it could be removed depending on the feedback received.