hi everyone,
i’ve created a class, and want it to be comparable with itself, but i
don’t
know what to place inside the <=> method.
the basic idea is that one of the values of the class (which is a
symbol) is
converted to a string, which is then compared.
greetings, Dirk.
On Dec 11, 2005, at 3:29 PM, Dirk M. wrote:
hi everyone,
i’ve created a class, and want it to be comparable with itself, but
i don’t
know what to place inside the <=> method.
the basic idea is that one of the values of the class (which is a
symbol) is
converted to a string, which is then compared.
Like this?
def <=>( other )
sym.to_s <=> other.sym.to_s
end
James Edward G. II
2005/12/11, James Edward G. II [email protected]:
Like this?
def <=>( other )
sym.to_s <=> other.sym.to_s
endJames Edward G. II
it works, thanks!
didn’t think it would be that simple…
greetings, Dirk.
Dirk M. wrote:
hi everyone,
i’ve created a class, and want it to be comparable with itself, but i
don’t
know what to place inside the <=> method.
the basic idea is that one of the values of the class (which is a
symbol) is
converted to a string, which is then compared.
The spaceship operator needs to return either
-1, 0 or 1 depending on whether it is ‘smaller’,
‘equal’ or ‘greater’ than the other object.
def <=>(other)
We can use String#<=> here if both are Strings.
Otherwise implement some custom comparison as above.
@my_value.to_s <=> other.to_s
end
greetings, Dirk.
E
Dirk M. ha scritto:
hi everyone,
i’ve created a class, and want it to be comparable with itself, but i don’t
know what to place inside the <=> method.
the basic idea is that one of the values of the class (which is a symbol) is
converted to a string, which is then compared.
greetings, Dirk.
yuu should return 1 if self > b, 0 if self == b and -1 otherwise.
You can generally realy on some other <=>, i.e.
Foo= Struct.new :someval do
?> def <=> othersomeval.to_s <=> other.someval.to_s
end
include Comparable
end
=> Foof1=Foo.new “ciao”
=> #f2=Foo.new “miao”
=> #f1 < f2
=> truef1 >= f2
=> false
hope this helps