Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Ruby expression with double ampersand using a return statement cause a syntax error

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?

like image 866
Dennis Avatar asked Dec 11 '22 08:12

Dennis


1 Answers

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.

like image 115
sawa Avatar answered Apr 27 '23 17:04

sawa