why I am getting void value expression error?

Code

[return 1]

And error from rib:

SyntaxError ((irb):3: void value expression)

same situation here:

def a[return 1 if true2]end
2

Best Answer


In order to construct the array, Ruby has to first evaluate the contents of the array. However, the contents of both arrays are a return expression which ends the evaluation of the method. In other words, the array will never be constructed, it is completely useless.

Ruby syntactically detects this situation, and makes it an error instead of executing useless code.

In Ruby, everything is an expression, which means everything has a value. However, for return, that puts us into a bit of a pickle: what should the value of the return expression be? Actually, it has no sensible value, because the current context is exited as soon as return is evaluated.

So, the value of return is assumed to be the void value, and whenever you use the void value in an expression context, i.e. where you would expect the value to be used further, that is an error.

You're trying to return a value that the parser can't determine. This is because the return is in the midst of an array definition.

Better might be...

return [1]

Or

def a[(my_boolean_method ? 1 : 2)]end