LoginSignup
1
0

More than 1 year has passed since last update.

rails 7.0で`Enumerable.sum`を使用した時に発生するdeprecated warning (Rails 7.0 has deprecated Enumerable.sum in favor of Ruby's native implementation available since 2.4.)について

Posted at

rails 7.0では数値以外のArrrayで第一引数を指定せずにEnumerable.sumを使用していた場合に以下のdeprecated warningが発生します。

Rails 7.0 has deprecated  Enumerable.sum in favor of Ruby's native implementation available since 2.4.
Sum of non-numeric elements requires an initial argument.

理由

rails 7.1からrails実装のEnumerable.sumがなくなりrubyのEnumerable.sumを呼び出すようになる為、数値以外のArrayに対しsumメソッドを呼び出す場合には第一引数が必須となります。

詳細

rubyのEnumerable.sumは第一引数に対して+メソッドを実行します。
この第一引数のデフォルトが0なので数値の場合はそのまま処理ができますが例えば文字列の場合は0に対してString+しようとするためTypeError発生します。

rails 7.1以前

inject(:+)された結果を返すので文字列の場合も結合可能

> ["a", "b"].sum
=> "ab"

rails 7.1以降

初期値0に対して文字列を+しようとしてエラーになる

> ['a', 'b'].sum
(irb):94:in `+': String can't be coerced into Integer (TypeError)
> ['a', 'b'].sum('')
=> "ab"
1
0
1

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