为什么 `puts(nil or 4)` 在 Ruby 中失败? [英] Why does `puts(nil or 4)` fail in Ruby?

查看:26
本文介绍了为什么 `puts(nil or 4)` 在 Ruby 中失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我这样做时:

puts(nil or 4)

Ruby 抱怨:

SyntaxError: syntax error, unexpected keyword_or, expecting ')'

这是为什么?puts(nil || 4) 确实有效,但我想知道为什么 or 没有.我认为两者之间的区别仅在于它们的运算符优先级.

Why is that? puts(nil || 4) does work, but I wonder why or doesn't. I thought the difference between the two was only in their operator precedence.

(我知道表达式 nil 或 4 似乎没什么用,因为它总是返回 4.为了简单起见,这只是一个例子.我的实际表达式是Integer(ENV['WD'] or 4).)

(I know the expression nil or 4 doesn't seem useful, as it always returns 4. It's just an example, for simplicity's sake. My actual expression is Integer(ENV['WD'] or 4).)

推荐答案

简短回答

因为 ruby​​ 语法就是这样.

Short answer

Because that's how ruby syntax is.

and/or 关键字被设计用于控制流结构.考虑这个例子:

and/or keywords were designed to be used in control flow constructs. Consider this example:

def die(msg)
  puts "Exited with: #{msg}"
end

def do_something_with(arg)
  puts arg
end

do_something_with 'foo' or die 'unknown error'
# >> foo
# >> Exited with: unknown error

这里 or 与 ruby​​ 的可选括号配合得很好,因为 ruby​​ 解析规则(伪BNF).

Here or works nicely with ruby's optional parentheses, because of ruby parsing rules (pseudo-BNF).

简而言之,参数列表(CALL_ARGS)是一个由逗号分隔的ARG列表.现在,大多数东西都是 ARG(类定义,例如,通过成为 PRIMARY),而不是简单的 EXPR.如果用括号将表达式括起来,那么它将匹配复合语句"的规则,因此将是一个 PRIMARY,它是一个 ARG.这意味着

In short, an argument list (CALL_ARGS) is a list of ARG, separated by comma. Now, most anything is an ARG (class definitions, for example, through being a PRIMARY), but not an unadorned EXPR. If you surround an expression with parentheses, then it'll match a rule for "compound statement" and, therefore, will be a PRIMARY, which is an ARG. What this means is that

puts( (nil or 4) ) # will work, compound statement as first argument
puts (nil or 4)  # same as above, omitted optional method call parentheses
puts(nil or 4) # will not work, EXPR can't be an argument
puts nil or 4 # will work as `puts(nil) or 4`

您可以阅读上面引用的语法以确切地理解它是如何工作的.

You can read the grammar referenced above to understand exactly how it works.

puts class Foo
       def bar
         puts "hello"
       end
     end, 'second argument'

# >> bar # this is the "value" of the class definition
# >> second argument

这篇关于为什么 `puts(nil or 4)` 在 Ruby 中失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆