You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby的`not`关键字究竟是什么?为何部分场景需加括号?

Ruby中not关键字的语法特性疑问

官方文档指出not是!的另一种写法,二者唯一区别是优先级不同。

Ruby解析器的代码定义了如下规则:

expr        : command_call
                | keyword_not '
'? expr
                    {
                        $$ = call_uni_op(p, method_cond(p, $3, &@3), METHOD_NOT, &@1, &@$);
                    /*% ripper: unary!(ID2VAL(idNOT), $:3) %*/
                    }

但实际使用时会发现,并非所有表达式都能直接用not,比如赋值语句里直接写x = not true会报错,几乎必须搭配括号才能合法使用,这是预期的设计吗?

下面是IRB中的测试示例(行为与MRI完全一致):

irb> x = !true
=> false

irb> not true
=> false

irb> x = !true
=> false

irb> x = not true
/Users/akim/.gem/ruby/3.3.0/gems/irb-1.12.0/lib/irb/workspace.rb:117:in `eval': (irb):3: syntax error, unexpected `true', expecting '(' (SyntaxError)
x = not true
        ^~~~

    from <internal:kernel>:187:in `loop'
    from /Users/akim/.gem/ruby/3.3.0/gems/irb-1.12.0/exe/irb:9:in `<top (required)>'
    from /opt/local/bin/irb:25:in `load'
    from /opt/local/bin/irb:25:in `<main>'

irb> x = not(true)
=> false

irb> x = (not true)
=> false

内容的提问来源于stack exchange,提问作者akim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 23:46:10