Nowicjusze będą mieli problem z metodami równości :
- a == b : sprawdza, czy a i b są równe. To jest najbardziej przydatne.
- a.eql? b : sprawdza również, czy a i b są równe, ale czasami jest bardziej rygorystyczne (może na przykład sprawdzać, czy a i b mają ten sam typ). Jest używany głównie w hashes.
- a. równy? b : sprawdza, czy a i b są tym samym obiektem (kontrola tożsamości).
- a === b : używane w instrukcjach case (czytam to jako „ a pasuje do b ”).
Te przykłady powinny wyjaśnić pierwsze 3 metody:
a = b = "joe"
a==b # true
a.eql? b # true
a.equal? b # true (a.object_id == b.object_id)
a = "joe"
b = "joe"
a==b # true
a.eql? b # true
a.equal? b # false (a.object_id != b.object_id)
a = 1
b = 1.0
a==b # true
a.eql? b # false (a.class != b.class)
a.equal? b # false
Zauważ, że == , eql? i równy?powinien być zawsze symetryczny: jeśli a == b to b == a.
Zauważ też, że == i eql?są zaimplementowane w klasie Object jako aliasy równe? , więc jeśli utworzysz nową klasę i chcesz == i eql? aby oznaczać coś innego niż zwykła tożsamość, musisz zastąpić je obie. Na przykład:
class Person
attr_reader name
def == (rhs)
rhs.name == self.name # compare person by their name
end
def eql? (rhs)
self == rhs
end
# never override the equal? method!
end
=== zachowuje się inaczej. Przede wszystkim jest to nie symetryczny (a === b jest nie oznacza, że B === A). Jak powiedziałem, a === b można odczytać jako „a pasuje do b”. Oto kilka przykładów:
# === is usually simply an alias for ==
"joe" === "joe" # true
"joe" === "bob" # false
# but ranges match any value they include
(1..10) === 5 # true
(1..10) === 19 # false
(1..10) === (1..10) # false (the range does not include itself)
# arrays just match equal arrays, but they do not match included values!
[1,2,3] === [1,2,3] # true
[1,2,3] === 2 # false
# classes match their instances and instances of derived classes
String === "joe" # true
String === 1.5 # false (1.5 is not a String)
String === String # false (the String class is not itself a String)
Instrukcja case oparta jest na metodzie === :
case a
when "joe": puts "1"
when 1.0 : puts "2"
when (1..10), (15..20): puts "3"
else puts "4"
end
jest równoważne z tym:
if "joe" === a
puts "1"
elsif 1.0 === a
puts "2"
elsif (1..10) === a || (15..20) === a
puts "3"
else
puts "4"
end
Jeśli zdefiniujesz nową klasę, której instancje reprezentują jakiś rodzaj kontenera lub zakresu (jeśli ma ona coś w rodzaju metody include? Lub match? ), Może okazać się przydatne zastąpienie metody === w następujący sposób:
class Subnet
[...]
def include? (ip_address_or_subnet)
[...]
end
def === (rhs)
self.include? rhs
end
end
case destination_ip
when white_listed_subnet: puts "the ip belongs to the white-listed subnet"
when black_listed_subnet: puts "the ip belongs to the black-listed subnet"
[...]
end