Darshan.Ishaya
11/23/2006 4:53:00 AM
Ah, thanks. I knew it would only work for classes with <=> defined, but
I was naively assuming all important classes did. (I've only been
playing with Ruby for a couple of weeks.) I didn't realize a class as
important as Symbol didn't have it.
I could try a slightly better, but probably similarly flawed:
def same_elems?(array1, array2)
return false unless array1.length == array2.length
compare = Proc.new do |x,y|
if (x.class == y.class)
if x.respond_to?('<=>')
x <=> y
else
x.to_s <=> y.to_s
end
else
x.class.to_s <=> y.class.to_s
end
end
return array1.sort(&compare) == array2.sort(&compare)
end
I'm now naively assuming all important classes implement to_s ; )
At least judging by this:
darshan@shadow ~ $ ri -T "<=>" | awk '{gsub(/<=>,/,"<=>\n");print}' |
grep "<=>" | wc -l
25
darshan@shadow ~ $ ri -T "to_s" | awk '{gsub(/to_s,/,"to_s\n");print}' |
grep "to_s$" | wc -l
116
it'll have a much better chance (almost 5 x) of working. (Sorry, I
haven't switched to Ruby one-liners yet; I'm sure I will soon.)
I guess it all depends on the application, and what classes are going to
be in the arrays. I sure had fun playing with it though. I'm so stoked
about Ruby.
Darshan
dblack@wobblini.net wrote:
> Hi --
>
> On Thu, 23 Nov 2006, Darshan.Ishaya wrote:
>
>> The Coolest Way:
>>
>> def same_elems?(array1, array2)
>> return false unless array1.length == array2.length
>>
>> compare = Proc.new do |x,y|
>> if (x.class == y.class)
>
> You'd probably want to throw in a "and if x.respond_to?('<=>')".
>
>> x <=> y
>> else
>> x.class.to_s <=> y.class.to_s
>
> The problem there is that it can't sort *within* a class that doesn't
> have <=> (and if it did, it would have sorted it that way :-) So, for
> example:
>
> p [:a,:b].sort(&compare) # => [:a,:b]
> p [:b,:a].sort(&compare) # => [:b,:a]
>
>
> David
>