Ruby Language
Porównywalny
Szukaj…
Składnia
-
include Comparable - zaimplementować operatora statku kosmicznego (
<=>)
Parametry
| Parametr | Detale |
|---|---|
| inny | Instancja, którą należy porównać do self |
Uwagi
x <=> y powinno zwrócić liczbę ujemną, jeśli x < y , zero, jeśli x == y a liczbę dodatnią, jeśli x > y .
Prostokąt porównywalny pod względem powierzchni
Comparable jest jednym z najpopularniejszych modułów w Rubim. Jego celem jest zapewnienie metod porównywania wygody.
Aby z niego skorzystać, musisz include Comparable i zdefiniować operatora statku kosmicznego ( <=> ):
class Rectangle
include Comparable
def initialize(a, b)
@a = a
@b = b
end
def area
@a * @b
end
def <=>(other)
area <=> other.area
end
end
r1 = Rectangle.new(1, 1)
r2 = Rectangle.new(2, 2)
r3 = Rectangle.new(3, 3)
r2 >= r1 # => true
r2.between? r1, r3 # => true
r3.between? r1, r2 # => false
Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow