LoginSignup
5
5

More than 5 years have passed since last update.

case文では && を and にそのまま書き換えられない

Posted at

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初心者の方はご注意ください。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5