Tbpgr Blog

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

Ruby | Enumerable | find_all

概要

Enumerable#find_all

詳細

Enumerable#find_all 評価が真になるブロックすべてを返却する

サンプル

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

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

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

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

  def detect_40
    self.find_all {|i|i == 40}
  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
出力
[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, 6, 9, 12, 15, 18, 21, 24, 27, 30]
[5, 10, 15, 20, 25, 30]
[15, 30]
[]