2
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 3 years have passed since last update.

【Ruby】odd? even? の使い方を学んで配列の中の偶数・奇数の数をカウントしよう!

Last updated at Posted at 2020-12-31

概要

配列から偶数 or 奇数の要素数のカウントの方法を学んでいきます。

目次

  • odd?

  • even?

  • Array#count

  • 実践

    • 問題
    • 解答(解説)
      • odd?
      • odd? + count
  • まとめ

  • 参考文献

odd?

対象の数値が奇数かどうかを判断するメソッドです。奇数であれば真を返し、そうでない場合は偽を返します。

even?

対象の数値が偶数かどうかを判断するメソッドです。偶数であれば真を返し、そうでない場合は偽を返します。

Array#count

配列の要素数を返します。

実践

問題

配列にある値から奇数の数をカウントして出力しよう!

解答(解説)

odd?
解答
def count_odds(nums) # 配列受け取り
  count = 0           # カウントした数を入れる 変数count を定義

  nums.each do |num|  # 配列から要素を一つずつ取り出す
    if num.odd?       # 取り出した値が奇数か?
      count += 1      # 値が奇数であれば 変数count に1を足していく
    end
  end
  p count             # eachの処理が終わったらcountを出力
end

# メソッド呼び出し
count_odds([3, 5, 2, 2, 1])
count_odds([3, 1, 0])
count_odds([2, 4, 6])

# ターミナル出力結果
# 3
# 2
# 0
odd? + count

上記よりもさらに簡単に書くことができます。

別解
def count_odds(nums)
  p nums.count { |num| num.odd? }
end

# メソッド呼び出し
count_odds([3, 5, 2, 2, 1])
count_odds([3, 1, 0])
count_odds([2, 4, 6])

# ターミナル出力結果
# 3
# 2
# 0

まとめ

  • odd?は対象の数値が奇数であれば真、そうでない場合は偽を返すメソッド
  • even?は対象の数値が偶数であれば真、そうでない場合は偽を返すメソッド
  • 配列にcountメソッドを使うことで、要素数を返すことができる

参考文献

2
1
4

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
2
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?