Module: Piggly::Util::Enumerable
- Defined in:
- lib/piggly/util/enumerable.rb
Class Method Summary collapse
-
.count(enum) ⇒ Object
Count number of elements, optionally filtered by a block.
-
.group_by(enum, collection = Hash.new{|h,k| h[k] = [] }) ⇒ Object
Collect an elements into disjoint sets, grouped by result of the block.
- .index_by(enum, collection = Hash.new) ⇒ Object
-
.sum(enum, default = 0, &block) ⇒ Object
Compute sum of elements, optionally transformed by a block.
Class Method Details
.count(enum) ⇒ Object
Count number of elements, optionally filtered by a block
6 7 8 9 10 11 12 |
# File 'lib/piggly/util/enumerable.rb', line 6 def self.count(enum) if block_given? enum.inject(0){|count,e| yield(e) ? count + 1 : count } else enum.length end end |
.group_by(enum, collection = Hash.new{|h,k| h[k] = [] }) ⇒ Object
Collect an elements into disjoint sets, grouped by result of the block
29 30 31 32 33 34 |
# File 'lib/piggly/util/enumerable.rb', line 29 def self.group_by(enum, collection = Hash.new{|h,k| h[k] = [] }) enum.inject(collection) do |hash, item| hash[yield(item)] << item hash end end |
.index_by(enum, collection = Hash.new) ⇒ Object
36 37 38 39 40 |
# File 'lib/piggly/util/enumerable.rb', line 36 def self.index_by(enum, collection = Hash.new) enum.inject(collection) do |hash, item| hash.update(yield(item) => item) end end |
.sum(enum, default = 0, &block) ⇒ Object
Compute sum of elements, optionally transformed by a block
15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/piggly/util/enumerable.rb', line 15 def self.sum(enum, default = 0, &block) enum = enum.to_a return default if enum.empty? head, *tail = enum if block_given? tail.inject(yield(head)){|sum,e| sum + yield(e) } else tail.inject(head){|sum,e| sum + e } end end |