Side Note
It is worth noting that and
and &&
are not equivalent.
and
is a flow control operator while &&
is a Boolean operator. What is the difference?
One example of the differences, using and
, you can assign values.
value = nil and value / 42
This would fail if you tried it as below
value = nil && value / 42
Original Question 1
Assuming I want to evaluate one-liners with a return statement (similar to a certain > commonly used shell/bash expression), would this be a recommended way to do it, or is there > a more recommended approach?
The way I have always seen this done in Ruby is this:
value if conditional
This will return the value if the conditional is met and nil
otherwise. No need for the return
statement if this is the last command in the function!
If you are using this for an early exit to a function, I prefer using an unless
. For instance...
return unless arguments_are_valid
Original Question 2
foo method causes a syntax error. bar doesn't. Why?
It's a matter of operator precedence. See the example below showing how they are evaluated.
(true && return) false
(true) and (return false)