Is there an implementation of the bag collection (a collection like a set, that kept count of how many times an object is inserted)?
Asked
Active
Viewed 1,431 times
5
-
I am looking for something that is as standard as possible. I would prefer a core library to a gem and a gem to code that is not even a gem. – Guillaume Coté Dec 20 '10 at 00:14
2 Answers
8
Sure! It's also called a multiset. Here's a nice ruby implementation.

mahemoff
- 44,526
- 36
- 160
- 222

Sam Ritchie
- 10,988
- 4
- 42
- 53
-
The documentation talks about running a script as root. Is there a ubuntu package that include it? – Guillaume Coté Dec 04 '10 at 03:58
-
not that I'm aware of... looks like you'll have to get the source from that side and build it on your end. – Sam Ritchie Dec 04 '10 at 04:02
-
1
6
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}>

Phrogz
- 296,393
- 112
- 651
- 745
-
-
1@AndrewGrimm Probably not noticeably slower given that this is a very lightweight shim on top of Hash, which is implemented in C. – Phrogz Dec 05 '10 at 14:33