Module: Enumerable
- Defined in:
- lib/ruby/enumerable.rb
Instance Method Summary collapse
-
#count(*args) ⇒ Integer
Count the number of elements that satisfy the predicate.
-
#sum(&block) ⇒ Object
Accumulate elements using the ‘+` method, optionally transforming them first using a block.
Instance Method Details
#count(*args) ⇒ Integer
Count the number of elements that satisfy the predicate
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
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 |