7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Ruby】配列の要素の平均値を求める

Last updated at Posted at 2019-12-22

配列arrayの平均値を求めるには、次のようにします。

array.sum.fdiv(array.length)

浮動小数点数の商が得られる Numeric#fdiv メソッドを用いて、配列の要素の合計(sum)を配列の要素数(length)で割ることで平均値が算出できます。

※単純に / を用いて商を計算しようとすると、整数 / 整数の場合、**整商(整数の商)**になってしまい正しい計算ができません。

例えば array = [2, 5] のとき、

array.sum.fdiv(array.length)
# => 3.5

ちなみに要素が文字列になっている場合は、to_iで整数型に変換してから計算すればOK。

例えば array = ["2", "5"] のとき、

array.map!(&:to_i) # 配列の要素を整数型に変換
# => [2, 5]

array.sum.fdiv(array.length)
# => 3.5

以上です。

※いただいたコメントを元に内容を修正させていただきました。
 @scivolaさん、ご指摘いただきありがとうございました。

7
1
2

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
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?