Programmering i Ruby

Den Pragmatiske Programmerers Veiledning

Forrige < Innhold ^
Neste >
modulen Comparable
Avhengig av: <=>

Indeks:

Sammenligninger between?


Modulen Comparable mikses inn i klasser hvor objektene kan sammenlignes og ordnes i en rekkefølge. Klassen må definere <=> operatoren, som sammenligner mottakeren med et annet objekt og returnerer -1, 0 eller +1 alt etter hvorvidt mottakeren er mindre enn, lik eller større enn det andre objektet. Comparable bruker <=> til å implementere de tradisjonelle sammenligningsoperatorene (<, <=, ==, >=, og >) samt metoden between?.

class SizeMatters
  include Comparable
  attr :str
  def <=>(anOther)
    str.size <=> anOther.str.size
  end
  def initialize(str)
    @str = str
  end
  def inspect
    @str
  end
end
s1 = SizeMatters.new("Z")
s2 = SizeMatters.new("YY")
s3 = SizeMatters.new("XXX")
s4 = SizeMatters.new("WWWW")
s5 = SizeMatters.new("VVVVV")
s1 < s2 » true
s4.between?(s1, s3) » false
s4.between?(s3, s5) » true
[ s3, s2, s5, s4, s1 ].sort » [Z, YY, XXX, WWWW, VVVVV]

instansmetoder
Sammenligninger anObject < otherObject -> true eller false
anObject <= otherObject -> true eller false
anObject == otherObject -> true eller false
anObject >= otherObject -> true eller false
anObject > otherObject -> true eller false

Sammenligner to objekter basert på mottakerens <=> metode.

between? anObject.between?( min, max ) -> true eller false

Returnerer false hvis anObject <=> min er mindre enn null eller hvis anObject <=> max er større enn null. Hvis ikke returneres true.

3.between?(1, 5) » true
6.between?(1, 5) » false
'cat'.between?('ant', 'dog') » true
'gnu'.between?('ant', 'dog') » false


Forrige < Innhold ^
Neste >

Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide".
Translation to norwegian by Norway Ruby User Group.
Copyright for the english original authored by David Thomas and Andrew Hunt:
Copyright © 2001 Addison Wesley Longman, Inc.
This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at
http://www.opencontent.org/openpub/).

(Please note that the license for the original has changed from the above. The above is the license of the original version that was used as a foundation for the translation efforts.)

Copyright for the norwegian translation:
Copyright © 2002 Norway Ruby User Group.
This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at
http://www.opencontent.org/openpub/).
Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.
Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.