Is there a bag implementation in Ruby?

Is there an implementation of a package collection (a collection similar to a collection that indicates the number of times the object is inserted)?

+5
source share
2 answers

Of course! It is also called multiset . Here's a good ruby ​​implementation.

+7
source

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}>
+6
source

All Articles