Feature #5574
closedMake arrays comparable
Description
Why are arrays not comparable? Array already defines <=>, so it seems only natural to mix-in the Comparable module.
> [1, 2] Array.send(:include, Comparable) > [1, 2] false
This was already discussed in the mailing list a while ago and people agreed it would be useful:
Updated by duerst (Martin Dürst) almost 13 years ago
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.
Updated by trans (Thomas Sawyer) almost 13 years ago
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.
Updated by trans (Thomas Sawyer) almost 13 years ago
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.
Updated by neleai (Ondrej Bilka) almost 13 years ago
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.
Updated by shevegen (Robert A. Heiler) almost 13 years ago
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?
Updated by mame (Yusuke Endoh) over 12 years ago
- Status changed from Open to Assigned
- Assignee set to matz (Yukihiro Matsumoto)
Updated by matz (Yukihiro Matsumoto) over 12 years ago
- 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.