Is there an implementation of the bag collection (a collection like a set, that kept count of how many times an object is inserted)?
问问题
1387 次
2 回答
8
当然!它也称为multiset。这是一个很好的 ruby 实现。
于 2010-12-04T03:41:49.267 回答
6
自己创建很简单,对吧?
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}>
于 2010-12-04T14:55:22.647 回答