为什么 "true || File.exist? 'touch'" 语法无效?
Why is "true || File.exist? 'touch'" invalid syntax?
以下无效:
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 ||
和不使用括号的组合是无效语法?
搜索 SyntaxError: unexpected tSYMBEG
只得到 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 and Ruby syntax error, unexpected tSTRING_BEG, expecting ':' (SyntaxError)
这会起作用
true or File.exist? 'touch'
之所以如此,是因为 ||
的优先级高于 or
,并且使用 ||
,您的表达式会简化为 (true || File.exist?) 'touch'
。
我不建议您使用 or
,但请考虑始终使用括号 - 大多数 Ruby 准则(Vanilla Ruby 和 Rails)完全建议使用它们次。
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.
以下无效:
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 ||
和不使用括号的组合是无效语法?
搜索 SyntaxError: unexpected tSYMBEG
只得到 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
这会起作用
true or File.exist? 'touch'
之所以如此,是因为 ||
的优先级高于 or
,并且使用 ||
,您的表达式会简化为 (true || File.exist?) 'touch'
。
我不建议您使用 or
,但请考虑始终使用括号 - 大多数 Ruby 准则(Vanilla Ruby 和 Rails)完全建议使用它们次。
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.