为什么"true || File.exist?'touch'"语法无效?

And*_*imm 2 ruby syntax syntax-error

以下内容无效:

true || File.exist? 'touch'
SyntaxError: unexpected tSTRING_BEG, expecting end-of-input
true || File.exist? 'touch'
                     ^
Run Code Online (Sandbox Code Playgroud)

但是,如果你删除true ||,或使用括号'touch',它是有效的:

File.exist? 'touch'
=> false

true || File.exist?('touch')
=> true
Run Code Online (Sandbox Code Playgroud)

为什么true ||使用和不使用括号的组合无效语法?

搜索SyntaxError: unexpected tSYMBEG只有https://github.com/bbatsov/rubocop/issues/1232,并且搜索SyntaxError: unexpected tSTRING_BEG似乎主要是让那些犯了某些拼写错误的人如RoR:语法错误,意外的tSTRING_BEG,期待')'Ruby语法错误,意外的tSTRING_BEG,期待':'(SyntaxError)

Mar*_*cny 7

这会奏效

true or File.exist? 'touch'
Run Code Online (Sandbox Code Playgroud)

原因是因为||具有更高的优先级or,并且与||您的表达式简化为(true || File.exist?) 'touch'.

我不建议您使用or,但考虑始终使用括号 - 大多数Ruby指南(Vanilla Ruby和Rails)建议始终使用它们.

社区驱动的红宝石风格指南:

省略围绕参数的括号,这些方法是内部DSL的一部分(例如Rake,Rails,RSpec),在Ruby中具有"关键字"状态的方法(例如attr_reader,puts)和属性访问方法.在所有其他方法调用的参数周围使用括号.