Bug #4517
closedArgumentError when sorting array of objects
Description
=begin
I've got some Rails (v. 3.0.4) code wherein an array of objects (referred to as 'Thing' here) need to be sorted:
stuff = array of Things
stuff.sort! {|a,b| a.value <=> b.value }
…where value is a String.
On Ruby 1.9.2p136 the array "stuff" is sorted successfully, but running the same code on 1.9.2p180 I get the following error:
ArgumentError (comparison of Thing with Thing failed)
I can reproduce the error in the console as well as when running the Rails application.
Thanks for taking a look.
=end
        
           Updated by ko1 (Koichi Sasada) over 14 years ago
          Updated by ko1 (Koichi Sasada) over 14 years ago
          
          
        
        
      
      Could you show the reproducible code?
        
           Updated by naruse (Yui NARUSE) over 14 years ago
          Updated by naruse (Yui NARUSE) over 14 years ago
          
          
        
        
      
      - Status changed from Open to Feedback
        
           Updated by jbl26 (Brian Lindauer) over 14 years ago
          Updated by jbl26 (Brian Lindauer) over 14 years ago
          
          
        
        
      
      =begin
I did some investigation into this. The following code does not trigger the error
class Thing
attr_accessor :value
def initialize(value)
@value = value
end
end
stuff = [Thing.new("Fred"), Thing.new("Wilma"), Thing.new("Barney")]
stuff.sort! {|a,b| a.value <=> b.value}
Reading through the Ruby source, I discovered that the only way this particular error text could be printed (in (({rb_cmperr()}))) would be if there was a comparison involving a numeric value, not just string/string comparison. Then I tried modifying the input array above to include a numeric value.
stuff = [Thing.new(4), Thing.new("Wilma"), Thing.new("Barney")]
stuff.sort! {|a,b| a.value <=> b.value}
This does, in fact, trigger the error.
in `sort!': comparison of Thing with Thing failed (ArgumentError)
I think the OP must have had a bug in his own code that resulted in a numeric-typed value in one of the instances of Thing.
=end
        
           Updated by nagachika (Tomoyuki Chikanaga) about 14 years ago
          Updated by nagachika (Tomoyuki Chikanaga) about 14 years ago
          
          
        
        
      
      - Status changed from Feedback to Third Party's Issue