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

为何&&运算符在Ruby哈希块中失效,而and运算符可正常工作?

问题解析:Ruby中&&与and在块中的执行差异

给定哈希:

hash = {a: 5, b: 10}

需求是检查哈希所有值是否为Integer类型且小于10,但两段代码执行结果完全不同:

hash.all?{|key,value| value.is_a? Integer && value < 10} # TypeError: class or module required from (pry):3:in `is_a?'

hash.all?{|key,value| value.is_a? Integer and value < 10} # false

核心原因:运算符优先级差异

这确实是运算符优先级导致的问题:

  • Ruby中&&的优先级远高于is_a?,第一段代码里的Integer && value < 10会优先执行:先计算value < 10得到布尔值,再和Integer做&&运算,最终is_a?接收的参数是这个布尔值(true或false),但is_a?要求传入类或模块,因此抛出TypeError。
  • and的优先级比is_a?低,第二段代码会先执行value.is_a? Integer得到布尔结果,再和value < 10做and逻辑运算,逻辑符合预期,最终返回false(因为b的值为10,不满足小于10的条件)。

正确的&&写法

如果要使用&&,需要通过括号明确优先级:

hash.all?{|key,value| (value.is_a? Integer) && value < 10} # 返回false,符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:09:24