Skip to content

Comparators (==, <, >, <=, >=) of subclassed Time instance do not call cmp defined on the subclass #6668

@hainesr

Description

@hainesr

When subclassing Time and overriding the <=> method the subclass is not using this new implementation when testing for equality (==). The expected behaviour is seen in MRI versions.

(Apologies if this has been reported already - I did check the 7 pages of issues mentioning Time but didn't spot it.)

Environment Information

  • JRuby version: jruby 9.2.14.0 (2.5.7) 2020-12-08 ebe64bafb9 OpenJDK 64-Bit Server VM 11.0.11+9-Ubuntu-0ubuntu2.20.04 on 11.0.11+9-Ubuntu-0ubuntu2.20.04 +jit [linux-x86_64]
  • Operating system and platform: Linux holdo 5.4.0-72-generic #80-Ubuntu SMP Mon Apr 12 17:35:00 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

Bare environment; no gems; run from irb

Test script:

class MyComp
  include Comparable

  attr_reader :value

  def initialize(val)
    @value = val
  end

  def <=>(other)
    self.value <=> other.value
  end
end

class NewComp < MyComp
  def <=>(other)
    warn "NewComp!"
    super(other)
  end
end

class NewTime < Time
  def <=>(other)
    warn "NewTime!"
    super(other)
  end
end

a = NewComp.new(6)
b = NewComp.new(6)
a == b

t = NewTime.now
u = NewTime.now
t == u

Expected Behavior

When run in MRI we see that in both cases the subclasses use the overridden <=> methods when compared with == (NewComp! and NewTime! are output):

2.7.2 :028 > a = NewComp.new(6)
 => #<NewComp:0x000055f1d72769f0 @value=6> 
2.7.2 :029 > b = NewComp.new(6)
 => #<NewComp:0x000055f1d73e2898 @value=6> 
2.7.2 :030 > a == b
NewComp!
 => true

2.7.2 :031 > t = NewTime.now; u = NewTime.now
 => 2021-05-09 17:13:45.110216419 +0100 
2.7.2 :032 > t == u
NewTime!
 => false

Actual Behavior

In JRuby we see that the first case agrees with MRI, but the subclassed Time is not using the overridden <=> (NewComp! is output but NewTime! is not):

jruby-9.2.14.0 :028 > a = NewComp.new(6)
 => #<NewComp:0x44aa91e2 @value=6> 
jruby-9.2.14.0 :029 > b = NewComp.new(6)
 => #<NewComp:0x650a1aff @value=6> 
jruby-9.2.14.0 :030 > a == b
NewComp!
 => true 

jruby-9.2.14.0 :031 > t = NewTime.now
 => 2021-05-09 17:30:43 +0100 
jruby-9.2.14.0 :032 > u = NewTime.now
 => 2021-05-09 17:30:43 +0100 
jruby-9.2.14.0 :033 > t == u
 => false

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions