The function that can be divided and assigned by right assignment of the development version of Ruby 3.0 has been added.

Reprinted from Blog Article.

It has entered. Originally, Ruby 2.7 experimentally included a function that allows split assignment using one line in of pattern matching.

# Ruby 2.Code that works with 7
p RUBY_DESCRIPTION
# => "ruby 2.7.2p137 (2020-10-01 revision 5445e04352) [x86_64-linux]"

data = { name: "homu", age: 14 }

#I was able to do split assignment using one line in
data in { name:, age: }
p name  # => "homu"
p age   # => 14

However, when pattern matching was officially introduced in Ruby 3.0, one line in was scheduled to be deleted once.

I thought it was a shame that split assignment was deleted because I wanted it because it is a very convenient function, but instead of deleting one line in, split assignment was implemented by right assignment in Ruby 3.0. This makes it possible to perform split assignment with right assignment, as was done with one line in.

p RUBY_DESCRIPTION
# => "ruby 3.0.0dev (2020-10-26T09:00:24Z master 52c630da00) [x86_64-linux]"

data = { name: "homu", age: 14 }
data => { name:, age: }
p name  # => "homu"
p age   # => 14

By the way, it is called split assignment, but since it is a variable capture function for pattern matching, it can also be used as follows.

data = { name: "homu", age: 14 }

#Only part can be assigned
data => { age: }
p age   # => 14

#Can also be captured with Struct
data = Struct.new(:name, :age).new("mami", 15)
data => { name: }
p name  # => "mami"

#Raise NoMatchingPatternError occurs if there is no match
data => { name: Integer }

Originally, I wanted to use one line in as a conditional expression for ʻif, but in the end it became unusable for that purpose, and on the contrary, it became a function with a slightly different meaning called split assignment. Since it was implemented by right assignment, it became a function with a different meaning, and I personally think that it has improved considerably. On the contrary, I want the function to be able to use true / false` so that it can be used in conditional expressions in one line in. For the time being, you can now use right substitution! !! By the way, will the left assignment be in the direction of split assignment?

Recommended Posts

The function that can be divided and assigned by right assignment of the development version of Ruby 3.0 has been added.
Ruby 2.7.2 has been released and deprecated warnings will no longer be issued by default
CircleCI configuration file that has been replaced by the operation of my own library
I tried a puzzle that can only be solved by the bottom 10% of bad engineers
The version of Ruby that was installed by default on the Mac was referenced, not from rbenv