From: Erik Hollensbe Date: 2008-10-03T14:00:32+09:00 Subject: Re: Ordered hash hack for < ruby 1.9? Lex Williams wrote: > Ben Johnson wrote: >> Patrick Doyle wrote: >>> Why not iterate over myhash.keys.sort instead of just myhash.keys? >>> >>> --wpd >> >> Because for performance it's bad. I don't care if performance is bad in >> my tests. Which is why it would be nice to alter how hashes work ONLY in >> my test environment. But sorting by keys isn't smart either. >> >>>> a = {:a => 1, :b => 2} >> => {:a=>1, :b=>2} >>>> a.keys.sort >> NoMethodError: undefined method `<=>' for :a:Symbol >> from (irb):16:in `sort' >> from (irb):16 >> from :0 > > Here's a hack for altering the original Hash class : > > class Hash > alias :old_equals :[]= > attr_reader :ordered_values > > def []=(key,value) > @ordered_values ||= [] > @ordered_values << key > old_equals(key,value) > end > > > end > > hsh = {} > hsh["a"]="b" > hsh["b"]="c" > hsh.ordered_values.each do |key| > puts key > end hsh.delete("a") hsh.ordered_values.each do |key| puts key end Does not output what you want. :) There are a number of recommended packages already that should do this, use one of them.. Not to mention this monkeypatch is going to slow down your whole program, when you likely just need it in one or two spots. If you do have to code it yourself, consider using the 'delegate' library (in stdlib) to wrap your specific, non-standard logic into its own class, where it can be managed separately from standard hashes. Yours in preventing senseless monkeypatching, -Erik -- Posted via http://www.ruby-forum.com/.