overriding the binary predicate when doing a lexicographical compare in ruby
If I have two arrays, a1 and a2 in ruby, to do a lexicographical comparison I do a1 <=> a2.
Is there a way to override how ruby compares each element?
What I'd like to do is something like
a1.collect(&:name) <=> a2.collect(&:name)
without the collect because that's creating two new arrays (e.g. if we开发者_高级运维're sorting an array of arrays, a ton of time would be spent in the allocator).
I could write my own lexicographical compare function, but that seems very anti-ruby and I'm not sure if it would be faster because the the amount of time spent in ruby space (vs C space).
edit: another example would be for doing a case insensitive lexicographical compare of two arrays of strings.
Pass a custom block to sort_by
instead:
meta_array = [a1, a2]
meta_array.sort_by do |arr|
arr.collect(&:name)
end
It's dangerous to change how arrays are compared, so you should create a subclass of Array
. Suppose your a1
and a2
belong to A
, which is a subclass of Array
. Then, redefine <=>
as follows:
class A; def <=> other; collect(&:name) <=> other.collect(&:name) end end
精彩评论