Rubyの論理演算子である &&
と and
は同じ動作をします。
たとえば、以下のようなメソッドであればどちらも同じ挙動になります。
def use_amp(a, b)
a && b
end
def use_and(a, b)
a and b
end
puts use_amp true, true # => true
puts use_amp true, false # => false
puts use_and true, true # => true
puts use_and true, false # => false
しかし、挙動は同じでも優先順位が異なる(and
の方が低い)ため、常に互換性があるとは限りません。
たとえば、case文の場合は &&
を and
にそのまま置き換えると構文エラーが発生します。
def case_amp(a, b)
case
when a && b
1
else
0
end
end
def case_and(a, b)
# 構文エラーが起きる
# syntax error, unexpected keyword_and, expecting keyword_then or ',' or ';' or '\n'
# when a and b
# ^
# warning: else without rescue is useless
# syntax error, unexpected keyword_end, expecting $end
case
when a and b
1
else
0
end
end
これを正しく動作させるためには、when (a and b)
のように括弧で囲む必要があります。
def case_amp(a, b)
case
when a && b
1
else
0
end
end
def case_and(a, b)
case
when (a and b)
1
else
0
end
end
puts case_amp true, true # => 1
puts case_amp true, false # => 0
puts case_and true, true # => 1
puts case_and true, false # => 0
この問題に遭遇した時、しばらくの間「なんで構文エラーになるんだ!?」と頭を抱えてしまったので、Ruby初心者の方はご注意ください。