初心者は平等法で問題を抱えるでしょう:
- a == b:aとbが等しいかどうかをチェックします。これは最も便利です。
- a.eql?b :aとbが等しいかどうかもチェックしますが、より厳密な場合もあります(たとえば、aとbが同じ型であることをチェックする場合があります)。主にハッシュで使用されます。
- a.equal?b:aとbが同じオブジェクトかどうかをチェックします(同一性チェック)。
- a === b:caseステートメントで使用されます(「aはbと一致する」と読みます)。
これらの例では、最初の3つの方法を明確にする必要があります。
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
なお、==、EQL?そして等しい?常に対称である必要があります。a== bの場合、b == aです。
==およびeqlにも注意してください。両方とも、等しいエイリアスとしてObjectクラスに実装されていますか?、それであなたが新しいクラスを作成し、==とeqlが欲しいなら?単純なアイデンティティ以外のものを意味するには、両方をオーバーライドする必要があります。例えば:
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
===方法は異なる動作をします。まず第一にそれは対称的ではありません(a === bはb === aを意味しません)。すでに述べたように、a === bは「aはbに一致する」と読むことができます。以下にいくつかの例を示します。
# === 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)
ケースの文が基づいている===方法:
case a
when "joe": puts "1"
when 1.0 : puts "2"
when (1..10), (15..20): puts "3"
else puts "4"
end
これと同等です:
if "joe" === a
puts "1"
elsif 1.0 === a
puts "2"
elsif (1..10) === a || (15..20) === a
puts "3"
else
puts "4"
end
インスタンスが何らかのコンテナまたは範囲を表す新しいクラスを定義する場合(include?またはmatch?メソッドのようなものがある場合)、次のように===メソッドをオーバーライドすると便利な場合があります。
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