LoginSignup
3
0

More than 1 year has passed since last update.

【Ruby のまずいコード】二乗和

Last updated at Posted at 2021-12-01

お題

数値配列の要素の 2 乗の和を返すメソッドを定義しよう。

コード

def square_sum(values)
  values.inject(0){ |sum, value| sum + value ** 2 }
end

改善

もっと簡素に書けます。

総和を求めるのに専用のメソッド Array#sum を使うとよいのですが,

def square_sum(values)
  values.map{ |value| value ** 2 }.sum
end

などとせずとも,sum のブロック付き用法で,

def square_sum(values)
  values.sum{ |value| value ** 2 }
end

と書けます。

番号指定ブロックパラメーターの導入された Ruby 2.7 以降なら

def square_sum(values)
  values.sum{ _1 ** 2 }
end

と書けます。

なお,Ruby 3.0 未満では数値の 2 乗を得るのに ** 2 とすると遅いので,

def square_sum(values)
  values.sum{ _1 * _1 }
end

と書くほうがよいでしょう。
Ruby 3.0 でも依然として後者のほうが少し速いので,速度がクリティカルな場合は後者の書き方にしましょう。
参考:Ruby 3.0 で x ** 2 が速くなった件 - Qiita

3
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
3
0