Feature #5574
closed
Added by tokland (Arnau Sanchez) about 13 years ago.
Updated over 12 years ago.
Description
Why are arrays not comparable? Array already defines <=>, so it seems only natural to mix-in the Comparable module.
> [1, 2] < [1, 1]
NoMethodError: undefined method `<' for [1, 2]:Array
> Array.send(:include, Comparable)
> [1, 2] < [1, 1]
=> false
This was already discussed in the mailing list a while ago and people agreed it would be useful:
http://www.ruby-forum.com/topic/76535
I support this proposal. In a basic programming lecture, I just recently told students how to compare (<, <=, and so on) numbers and strings, and then mentioned that it would work the same way for Arrays. But then when I wanted to show this, it didn't work.
I was quite surprised, because I had sorted Arrays many times before. Then I vaguely remembered: Ah, yes, there's a <=> operator for Arrays, but if you want to use <, <=, ..., you have to include Comparable. It's the way it currently is, but it's totally unclear why, and it's difficult to remember.
Ruby Facets provides a Tuple class, which is an immutable Array that is also Comparable. I believe I may have suggested Ruby provide such a class in the past. If Array can not be Comparable for some reason, perhaps this is a reasonable alternative.
Ruby Facets provides a Tuple class, which is an immutable Array that
is also Comparable. I believe I may have suggested Ruby provide such a
class in the past. If Array can not be Comparable for some reason,
perhaps this is a reasonable alternative.
I remember that in ruby-core long ago matz explained that array don't include comparable because they could contain elements that are not comparable.
I dont see this as problem as this is violated in most classes when comparing field that can be nil.
Ok so it does not yet exist because it can contain elements that are not comparable.
But in the example given with the 1, 2] < [1, 1] all elements are comparable. Ruby wants you to include Comparable.
But even when you do that, and then try to compare an invalid Array element:
[1, 2] < [1, "adc"]
You get an argument error:
ArgumentError: comparison of Array with Array failed
So I think the better way would be to include Comparable module in Array?
- Status changed from Open to Assigned
- Assignee set to matz (Yukihiro Matsumoto)
- Status changed from Assigned to Rejected
Since arrays are not always compatible, I don't want to give wrong implication by making arrays comparable.
Adding <=> was a realistic compromise for me to allow array sorting.
Matz.
Also available in: Atom
PDF
Like0
Like0Like0Like0Like0Like0Like0Like0