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)
x <=> y
else
x.class.to_s <=> y.class.to_s
end
end
return array1.sort(&compare) == array2.sort(&compare)
end
Ruby sure is fun. Like I said, I'm new to Ruby, so I'm still getting a
kick out of all this stuff. I'm pretty sure this works (i.e, meets all
of your criteria), and man do I think it's cool that you can do this.
Remember I said you could pass a block to sort()? Well, I just did
what I wanted (I'm not used to being ABLE to do what I want, Ruby seems
to make it way easier to just tell it to do what you want it to.)
I guess it'll work for any two arrays filled with objects of any
classes that have <=> defined. That should be most, I think. I just
tell sort() to compare with <=> if the objects to be compared are of
the same class, and if not, sort by putting the one whose class name
comes first alphabetically (converting their class names to Strings and
comparing those with <=>). So you get a sorted array with, e.g. Arrays
first, then Fixnums, then Stings, then Symbols, or whatever, but
classes in order, and in order within the classes.
It's conceptually simple, but I have no idea how it compares in speed
to the other ways. Can anyone give me a tip on a good way to
benchmark?
Darshan