If I do this:
(false true)
it fails with a syntax error, as I expect. But if I do this:
(false
true)
the code is executed, and it throws away the first condition and returns the result of the second.
Is this considered a bug or a feature?
If I do this:
(false true)
it fails with a syntax error, as I expect. But if I do this:
(false
true)
the code is executed, and it throws away the first condition and returns the result of the second.
Is this considered a bug or a feature?
Line endings are optional, so in this case, the return is causing the parser to interpret it as the following:
(false; true)
which evaluates to just:
(true)
If these were method calls then both would be evaluated, but only the last would be emitted. For example:
x = (p "hello"
p "world"
2)
This will output "hello" and "world" and x will equal 2
Parentheses are used for grouping, line breaks are used as expression separators. So, what you have here is simply a group of two expressions. There is nothing to reject.
This is useful because of this well-known idiom:
def foo(bar = (bar_set = true; :baz))
if bar_set
# optional argument was supplied
end
end
There is simply no other way in Ruby to figure out whether an optional argument was supplied or not.
Basically, this becomes interesting in the presence of side effects, such as assigning a variable in my example or printing to the screen in @32bitkid's example. In your example, there is no side effect, that's why you couldn't see what was actually going on.
Ruby can give you a warning if you have warnings on.
$VERBOSE = true
def foo
(false
true)
end
gives you
(irb):3: warning: unused literal ignored
In both Ruby 1.9.1 patchlevel 378 and Ruby 1.8.7 patchlevel 330.
See How can I run all Ruby scripts with warnings? for how to run all Ruby scripts with warnings on.