From: Tim Garnett Date: 2010-10-21T02:04:56+09:00 Subject: Re: YAML serialization of Hash with Set key not loadable Thanks all for the help. Good to know that the issue is fixed in ruby 1.9.2 Psych library. I'll have try our switching our Rails app to that when we upgrade to 1.9.2. set seems to get no love sometimes, I remember back in ruby 1.8.6 it didn't even hash correctly (i.e. in 1.8.6 which we were stuck on for a long time [1,2,3].to_set == [3,2,1].to_set => true [1,2,3].to_set.hash == [3,2,1].to_set.hash => false ). That at least was fixed in ruby 1.8.7/1.9. My workaround back then was to use sorted uniqued arrays as the key, which is what I'll continue to do for the yaml bug too. --- As to why you might use the set class as a hash key, in ruby any object can be used as a hash key (assuming it implements hash consistently) and set is a good way to represent a list of unique things where the order doesn't matter. For a made up example I want to cache some computed value in a hash that depends on a set of parameters with no order dependency. Say the sum of 3 unique values. require 'set' require 'pp' def foo(a,b,c) (@cached ||= {})[[a,b,c].to_set] ||= (sleep 10 ; [a,b,c].inject(&:+)) end foo(1,2,3) =>6 (slow, 10 seconds) foo(1,2,3) =>6 (fast cached) foo(3,2,1) =>6 (fast cached) pp @cached {#=>6} If you used an array as the cache key instead of a set then the order would matter and foo(3,2,1) would have been slow and @cached larger. My actual use case is for something vaguely like this (very expensive computation on list of unique elements where order doesn't matter) -- Posted via http://www.ruby-forum.com/.