From: Joel VanderWerf Date: 2009-07-28T04:02:38+09:00 Subject: Re: Set class and repetetive elements Marcin G坦rski wrote: > Hi, > I would like to know if there is possibility to add values like but have > a few elemens with the same value: > > irb(main):002:0> require 'set' > => true > irb(main):003:0> a = Set.new > => # > irb(main):004:0> a.add(1) > => # > irb(main):005:0> a.add(1) > => # > irb(main):006:0> a.add(1) > => # > irb(main):007:0> a.add(2) > => # > irb(main):008:0> a.add(3) > => # > irb(main):009:0> a.add(4) > => # > irb(main):010:0> a.add(5) > => # > irb(main):011:0> a.add(6) > => # > irb(main):012:0> a.add(1) > => # > > It would be nice to have for example {5, 1, 1, 1} in Set class object. > Is it possible? Which method should I use to add element in that way? You can build something based on hashes (Set is itself based on Hash): class Bag def initialize @h = {} end def add val (@h[val] ||= []) << val end def [](key) @h[key] end def inspect "#" end end bag = Bag.new bag.add 1 bag.add 1 bag.add 1 bag.add 2 bag.add 2 bag.add 3 p bag # ==> # -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407