2

The following is invalid:

true || File.exist? 'touch'
SyntaxError: unexpected tSTRING_BEG, expecting end-of-input
true || File.exist? 'touch'
                     ^

However, if you remove the true ||, or use brackets around 'touch', it's valid:

File.exist? 'touch'
=> false

true || File.exist?('touch')
=> true

Why is the combination of the true || and not using brackets invalid syntax?

Doing a search for SyntaxError: unexpected tSYMBEG only got https://github.com/bbatsov/rubocop/issues/1232 , and doing a search for SyntaxError: unexpected tSTRING_BEG seemed to mainly get people who'd made some sort of typo such as RoR: syntax error, unexpected tSTRING_BEG, expecting ')' and Ruby syntax error, unexpected tSTRING_BEG, expecting ':' (SyntaxError)

Community
  • 1
  • 1
Andrew Grimm
  • 70,470
  • 47
  • 186
  • 310

1 Answers1

7

This will work

true or File.exist? 'touch'

The reason is does is because || has higher precedence than or, and with || your expression simplifies to (true || File.exist?) 'touch'.

I'm not recommending you use or, but consider always using parenthesis - most Ruby guidelines (Vanilla Ruby and Rails) recommend using them at all times.

Community driven ruby style guide:

Omit parentheses around parameters for methods that are part of an internal DSL (e.g. Rake, Rails, RSpec), methods that have "keyword" status in Ruby (e.g. attr_reader, puts) and attribute access methods. Use parentheses around the arguments of all other method invocations.

Martin Konecny
  • 50,691
  • 18
  • 119
  • 145