Creating a <=> method

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.

Like this?

def <=>( other )
   sym.to_s <=> other.sym.to_s
end

James Edward Gray II

···

On Dec 11, 2005, at 3:29 PM, Dirk Meijer 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.

Dirk Meijer 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 <=> other
>> someval.to_s <=> other.someval.to_s
>> end
>> include Comparable
>> end
=> Foo
>> f1=Foo.new "ciao"
=> #<struct Foo someval="ciao">
>> f2=Foo.new "miao"
=> #<struct Foo someval="miao">
>> f1 < f2
=> true
>> f1 >= f2
=> false

hope this helps

Dirk Meijer 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

···

--
Posted via http://www.ruby-forum.com/\.

it works, thanks! :smiley:
didn't think it would be that simple..
greetings, Dirk.

···

2005/12/11, James Edward Gray II <james@grayproductions.net>:

Like this?

def <=>( other )
  sym.to_s <=> other.sym.to_s
end

James Edward Gray II