Question

def foo
  true && return false
end

def bar
  true and return false
end

foo method causes a syntax error. bar doesn't. Why?

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?

Was it helpful?

Solution 2

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)

OTHER TIPS

By operator associativity strength,

true && return false

evaluates to

(true && return) false

of which

true && return

is valid, but the false after it is invalid. You cannot have two statements lined up without anything in between.

Because of the && operator precedence, the following line

true && return false

evaluates as

(true && return) false

that does not makes sense. In order to execute your code you need to use

def foo
  true && (return false)
end

and doesn't suffer of the same issue because and has lower precedence than &&.

if there is need for shorten statements use

def foo
  return false if true
end

def bar
  return false if true
end

return is not a function :) therefore it doesn't make sense to say

when true and return is ok send a false
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top