How to - Change operator behaviour

H

Henry Savr

Dear Ruby gurus:

I want to write anywhere in my code t1 > t2 and get:
- true if at least one parameter is nil and the other parameter is
Time
- standard comparision result in other case


How to do that?

Thank you
Henry
 
H

Henry Savr

Mark said:
In your example, you would be calling the method '>' on t1...

t1.>(t2)

You can define > in the class you would like to have your functionality
in.

class Example
def >( other )
#do soem comparison
end
end


Sorry, I see, that my initial question was not asked clearly.
I know about the "> trick."

The question actually was:

I want to redefine a Time method >

It's new behaviour should be like this:

class Time1 < Time
def >(other)
case other.class.name
when "Time"
return self > other # but use the OLD > method definition.
when ("NilClass")
return true
else
# do what Ruby does originally in this case : when one operand is
Time, and other not the Time.
end
end

So question was
1. How to instruct Ruby to use OLD definition?
2. a)What Ruby does if it sees one parameter of Time class and other
non-Time?
b)How to say him to do the same?
Thank you

Henry
 
S

Simen Edvardsen

It's new behaviour should be like this:

class Time1 < Time
def >(other)
case other.class.name
when "Time"
return self > other # but use the OLD > method definition.
when ("NilClass")
return true
else
# do what Ruby does originally in this case : when one operand is
Time, and other not the Time.
end
end

Unrelated hat tip: many classes define the #=== method, for "case
equality", and it's used in case statements. Your code could be
simplified to

case other
when Time
self > other
when NilClass
true
end
 
D

Daniel Schierbeck

Henry said:
Sorry, I see, that my initial question was not asked clearly.
I know about the "> trick."

The question actually was:

I want to redefine a Time method >

It's new behaviour should be like this:

class Time1 < Time
def >(other)
case other.class.name
when "Time"
return self > other # but use the OLD > method definition.
when ("NilClass")
return true
else
# do what Ruby does originally in this case :
# when one operand is Time, and other not the Time.
end
end

class Time
def > other
if other.nil?
true
else
(self <=> other) == 1
end
end
end


Cheers,
Daniel
 
L

Logan Capaldo

class Time1 < Time
def >(other)
case other.class.name
when "Time"
return self > other # but use the OLD > method definition.
return super

Ahh, the joys of inheritence
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,209
Messages
2,571,089
Members
47,689
Latest member
kilaocrhtbfnr

Latest Threads

Top