Module: Enumerable

Defined in:
lib/ruby/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#count(*args) ⇒ Integer

Count the number of elements that satisfy the predicate

Examples:

["abc", "de", "fg", "hi"].count{|s| s.length == 2 } #=> 3
["a", "b", "a", "c", "a"].count("a")                #=> 3
[1, 3, 5, 9, 0].count                               #=> 5

Returns:



11
12
13
14
15
16
17
18
19
# File 'lib/ruby/enumerable.rb', line 11

def count(*args)
  if block_given?
    inject(0){|n, e| yield(e) ? n + 1 : n }
  elsif args.empty?
    size
  else
    inject(0){|n, e| e == args.first ? n + 1 : n }
  end
end

#sum(&block) ⇒ Object

Accumulate elements using the ‘+` method, optionally transforming them first using a block

Examples:

["a", "b", "cd"].sum             #=> "abcd"
["a", "b", "cd"].sum(&:length)   #=> 4


28
29
30
31
32
33
34
# File 'lib/ruby/enumerable.rb', line 28

def sum(&block)
  if block_given?
    tail.inject(yield(head)){|sum,e| sum + yield(e) }
  else
    tail.inject(head){|sum,e| sum + e }
  end
end