Module: Enumerable

Defined in:
lib/utilities/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#collect_first(amount = nil, &block) ⇒ Object Also known as: map_first

Collects the first N truthy values {}.collect_first {|a, b| obj} => obj {}.collect_first(n) {|a, b| obj} => [obj]



5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/utilities/enumerable.rb', line 5

def collect_first( amount = nil, &block )
  array = !amount.nil?
  amount ||= 1
  
  values = []
  self.each do |val|
    break if values.length >= amount
    t = yield(val)
    values << t if t
  end
  
  !array && amount == 1 ? values.first : values
end