💎

Ruby 3.2 - 代入式の評価順 / パターンマッチ

2022/12/03に公開

Ruby 3.2 アドベントカレンダーの3日目の記事です。

https://qiita.com/advent-calendar/2022/ruby32


代入式の評価順

Bug #15928: Constant declaration does not conform to JIS 3017:2013 - Ruby master - Ruby Issue Tracking System

定数設定時、定数の定義元オブジェクトと代入する式の評価順が変更された。

def foo
  p :foo
  Object
end

def bar
  p :bar
end

foo::Hoge = bar

上のスクリプトを実行すると次の出力になる。

Ruby 3.1:

:bar
:foo

右辺が先に評価されてる。これが 3.2 では変更になり、

Ruby 3.2:

:foo
:bar

代入式では必ず左辺が先に評価されるということになったっぽい。

パターンマッチ

Feature #18585: Promote find pattern to official feature - Ruby master - Ruby Issue Tracking System

パターンマッチの Find pattern というやつが正式機能になった。

a = ['a', 1, 'b', 2, 'c', 3]
a in [*, Integer => x, String => y, *]
p [x, y]  #=> [1, "b"]

Ruby 3.1 だと

warning: Find pattern is experimental, and the behavior may change in future versions of Ruby!

という警告が出ていたが、3.2 だと出なくなった。

* で任意のオブジェクトを指定できるってことなのかな。パターンマッチ全然わからん。

Discussion