Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Avraam Mavridis
Avraam Mavridis

Posted on

     

CodeTip - Ruby: Compare class instances

In theprevious post I wrote about how to compare objects in Javascript. In Ruby we can do the same using the Comparable module. We include the comparable module in our class and we define a pseudooperator-method<=>. Let’s say we have again a Car class that looks like this:

classCarattr:speeddefinitialize(speed)@speed=speedendend

And now let’s make their instances comparable by including the Comparable module and defining the<=> pseudooperator.

classCarincludeComparableattr:speeddef<=>(other)self.speed<=>other.speedenddefinitialize(speed)@speed=speedendendcar1=Car.new(100)car2=Car.new(120)car3=Car.new(90)pcar2>car1# truepcar3>car2# falsecars=[car1,car2,car3]pcars.sort()# [#<Car:0x000055aec8add4b0 @speed=90>, #<Car:0x000055aec8add500 @speed=100>, #<Car:0x000055aec8add4d8 @speed=120>]

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

More fromAvraam Mavridis

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp