Search code examples
rubyreturnoperator-precedenceor-operator

Why is `return a or b` a void value expression error in Ruby?


This is just fine:

def foo
  a or b
end

This is also fine:

def foo
  return a || b
end

This returns void value expression:

def foo
  return a or b
end

Why? It doesn't even get executed; it fails the syntax check. What does void value expression mean?


Solution

  • return a or b is interpreted as (return a) or b, and so the value of return a is necessary to calculate the value of (return a) or b, but since return never leaves a value in place (because it escapes from that position), it is not designed to return a valid value in the original position. And hence the whole expression is left with (some_void_value) or b, and is stuck. That is what it means.