5

Is there an implementation of the bag collection (a collection like a set, that kept count of how many times an object is inserted)?

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Guillaume Coté
  • 2,761
  • 2
  • 21
  • 28
  • I am looking for something that is as standard as possible. I would prefer a core library to a gem and a gem to code that is not even a gem. – Guillaume Coté Dec 20 '10 at 00:14

2 Answers2

8

Sure! It's also called a multiset. Here's a nice ruby implementation.

mahemoff
  • 44,526
  • 36
  • 160
  • 222
Sam Ritchie
  • 10,988
  • 4
  • 42
  • 53
6

Pretty simple to create on your own, right?

class Bag
  def initialize
    @h = Hash.new{ 0 }
  end
  def <<(o)
    @h[o] += 1
  end
  def [](o)
    @h[o]
  end
end

bag = Bag.new
bag << :a
bag << :b
bag << :a
p bag[:a], bag[:b], bag[:c], bag
#=> 2
#=> 1
#=> 0
#=> #<Bag:0x100138890 @h={:b=>1, :a=>2}>
Phrogz
  • 296,393
  • 112
  • 651
  • 745