1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】Integerの=~でエラーが出る

Posted at

はじめに

Ruby 3.2 では、Integer クラスにおける =~ 演算子の使用ができなくなりました。これにより、以前のバージョンで動作していたコードがエラーを引き起こす可能性があります。

=~ 演算子とは?

=~ は Ruby で主に正規表現マッチングに使用される演算子であり、通常は StringRegexp のマッチング処理に使用されます。

puts 'hello' =~ /ell/  #=> 1 (マッチした位置を返す)
puts 'hello' =~ /xyz/  #=> nil (マッチしない場合は nil)

以前の Ruby では、Integer=~ を使用すると nil を返していました。

puts 42 =~ /42/  #=> nil (Ruby 3.1 以前ではエラーにならない)

しかし、Ruby 3.2 ではこの動作が削除され、Integer に対して =~ を使用するとエラーが発生します。

Ruby 3.2 における変更点

Ruby 3.2 では、Integer クラスにおける =~ のサポートが削除され、以下のようなコードは NoMethodError を引き起こします。

Ruby 3.1 以前

42 =~ /42/  #=> nil (特に意味はないがエラーにはならない)

Ruby 3.2 以降

42 =~ /42/  #=> NoMethodError: undefined method `=~' for 42:Integer

回避策

IntegerRegexp の比較を行う場合は、明示的に to_s を使用する。

42.to_s =~ /42/  #=> 0

参考

https://zenn.dev/tmtms/articles/202212-ruby32-5#object%23%3D~

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?