Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Enumerable | detect/find

概要

Enumerable#detect/find

詳細

Enumerable#detect/find ブロックで指定した条件に一致する最初の要素を探します。
ブロックに引数を指定した場合は未発見時の処理を指定出来ます。
※デフォルトでは未発見時はnilを返却する。

サンプル

コード
# encoding: utf-8
require "pp"

class Array
  def first_fizze
    self.detect {|i|i % 3 == 0}
  end

  def first_buzz
    self.detect {|i|i % 5 == 0}
  end

  def first_fizz_buzz
    self.detect {|i|i % 5 == 0 && i % 3 == 0}
  end

  def detect_40(proc = nil)
    if proc.nil?
      self.detect {|i|i == 40}
    else
      self.detect(proc) {|i|i == 40}
    end
  end
end

list = []
30.times {|i|list << i + 1}
p list
p list.first_fizze
p list.first_buzz
p list.first_fizz_buzz
p list.detect_40
p list.detect_40 lambda{"no 40"}
出力
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
3
5
15
nil
"no 40"