Forum: Ruby creating a <=> method

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dirk M. (Guest)
on 2005-12-11 23:30
(Received via mailing list)
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.
James G. (Guest)
on 2005-12-11 23:36
(Received via mailing list)
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
gabriele renzi (Guest)
on 2005-12-11 23:39
(Received via mailing list)
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 <=> 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 M. (Guest)
on 2005-12-11 23:42
(Received via mailing list)
2005/12/11, James Edward G. II <removed_email_address@domain.invalid>:
>
> Like this?
>
> def <=>( other )
>   sym.to_s <=> other.sym.to_s
> end
>
> James Edward G. II


it works, thanks! :D
didn't think it would be that simple..
greetings, Dirk.
Eero S. (Guest)
on 2005-12-11 23:43
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
This topic is locked and can not be replied to.