Class: Collectr::Bag
Instance Method Summary collapse
- #<<(obj) ⇒ Object
- #[](obj) ⇒ Object
- #add(obj) ⇒ Object
- #as_sorted_counts ⇒ Object
- #bag ⇒ Object
- #count ⇒ Object
- #each(&block) ⇒ Object
- #empty? ⇒ Boolean
-
#initialize(collection = nil) ⇒ Bag
constructor
A new instance of Bag.
- #keys ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize(collection = nil) ⇒ Bag
Returns a new instance of Bag.
5 6 7 8 |
# File 'lib/collectr/bag.rb', line 5 def initialize(collection=nil) @bag = Hash.new{ 0 } collection.each{ |item| self << item } if collection end |
Instance Method Details
#<<(obj) ⇒ Object
15 16 17 |
# File 'lib/collectr/bag.rb', line 15 def <<(obj) add(obj) end |
#[](obj) ⇒ Object
19 20 21 |
# File 'lib/collectr/bag.rb', line 19 def [](obj) @bag[obj] end |
#add(obj) ⇒ Object
10 11 12 13 |
# File 'lib/collectr/bag.rb', line 10 def add(obj) @bag[obj] += 1 self end |
#as_sorted_counts ⇒ Object
49 50 51 |
# File 'lib/collectr/bag.rb', line 49 def as_sorted_counts @bag.sort_by{ |key, cnt| -cnt } end |
#bag ⇒ Object
41 42 43 |
# File 'lib/collectr/bag.rb', line 41 def bag @bag end |
#count ⇒ Object
31 32 33 34 35 |
# File 'lib/collectr/bag.rb', line 31 def count sum = 0 each{ |key, val| sum += val } sum end |
#each(&block) ⇒ Object
37 38 39 |
# File 'lib/collectr/bag.rb', line 37 def each(&block) @bag.each{ |k,v| block.call k,v } end |
#empty? ⇒ Boolean
45 46 47 |
# File 'lib/collectr/bag.rb', line 45 def empty? @bag.empty? end |
#keys ⇒ Object
23 24 25 |
# File 'lib/collectr/bag.rb', line 23 def keys @bag.keys end |
#size ⇒ Object
27 28 29 |
# File 'lib/collectr/bag.rb', line 27 def size @bag.size end |