Is there an implementation of the bag collection (a collection like a set, that kept count of how many times an object is inserted)?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Sure! It's also called a multiset. Here's a nice ruby implementation.
回答2:
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}>