为什么"是真的|| File.exist? '触摸'"无效的语法?

时间:2016-01-04 04:58:33

标签: ruby syntax syntax-error

以下内容无效:

.ScaleAspectFit

但是,如果您删除了true || File.exist? 'touch' SyntaxError: unexpected tSTRING_BEG, expecting end-of-input true || File.exist? 'touch' ^ ,或使用true ||周围的括号,则它有效:

'touch'

为什么File.exist? 'touch' => false true || File.exist?('touch') => true 和不使用括号的组合无效语法?

搜索true ||只获得https://github.com/bbatsov/rubocop/issues/1232,搜索SyntaxError: unexpected tSYMBEG似乎主要是让那些犯了某些错字的人,例如{{3} }和RoR: syntax error, unexpected tSTRING_BEG, expecting ')'

1 个答案:

答案 0 :(得分:7)

这将有效

true or File.exist? 'touch'

原因是因为||的优先级高于or,而||的表达式简化为(true || File.exist?) 'touch'

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

Community driven ruby style guide

  

忽略了作为内部DSL(例如Rake,Rails,RSpec)一部分的方法的参数的括号,以及具有"关键字" Ruby中的状态(例如attr_reader,puts)和属性访问方法。 在所有其他方法调用的参数周围使用括号。