开发者

Is there a bag implementation in Ruby?

开发者 https://www.devze.com 2023-01-28 15:51 出处:网络
Is there an implementation of the b开发者_如何转开发ag collection (a collection like a set, that kept count of how many times an object is inserted)?Sure! It\'s also called a multiset. Here\'s a nice

Is there an implementation of the b开发者_如何转开发ag collection (a collection like a set, that kept count of how many times an object is inserted)?


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


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}>
0

精彩评论

暂无评论...
验证码 换一张
取 消