Class: Collectr::Bag

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/collectr/bag.rb

Instance Method Summary collapse

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_countsObject



49
50
51
# File 'lib/collectr/bag.rb', line 49

def as_sorted_counts
  @bag.sort_by{ |key, cnt| -cnt }
end

#bagObject



41
42
43
# File 'lib/collectr/bag.rb', line 41

def bag
  @bag
end

#countObject



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

Returns:

  • (Boolean)


45
46
47
# File 'lib/collectr/bag.rb', line 45

def empty?
  @bag.empty?
end

#keysObject



23
24
25
# File 'lib/collectr/bag.rb', line 23

def keys
  @bag.keys
end

#sizeObject



27
28
29
# File 'lib/collectr/bag.rb', line 27

def size
  @bag.size
end