6

Ruby 3.1 evaluates multiple assignments from left to right

 3 years ago
source link: https://blog.saeloun.com/2021/05/12/ruby-evaluate-multiple-assignment-left-hand-side-before-right
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Ruby 3.1 evaluates multiple assignments from left to right

May 12, 2021 , by Jijo Bose
1 minute read

Single assignment

In the case of single assignment, Ruby evaluates the left-hand side before the right-hand side.

In the below example, the last expression calls lists, then data , then []= on the result of lists.

  lists = ['ruby', 'python', 'scala']
  data = 'rust'
  lists[1] = data

Before

Multiple assignments didn’t work this way. Let’s checkout the below example.

  lists[1], tag.priority = data, num

Before Ruby 3.1, the above expression would be evaluated in the following order:

  1. data
  2. num
  3. lists
  4. []= called on the result of lists
  5. tag
  6. priority= called on the result of the tag

After

Starting with Ruby 3.1, multiple assignments evaluation order has been made consistent with single assignment evaluation order.

  lists[1], tag.priority = data, num

For the above expression, the left-hand side is evaluated before the right-hand side and the order is as below:

  1. lists
  2. tag
  3. data
  4. num
  5. []= called on the result of lists
  6. priority= called on the result of the tag

Share this post!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK