Is there a bag implementation in Ruby?

人走茶凉 提交于 2019-12-06 02:43:49

问题


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


来源:https://stackoverflow.com/questions/4351793/is-there-a-bag-implementation-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!