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

如何统计Ruby数组哈希中:selected_person为true的出现次数?

统计数组哈希中:selected_person值为true的次数

起始代码

output = [{:selected_person=>true,
           :full_name=>"Fn G猫gèksöugöynúõr Ln Ýüćėūpàøehwìėwo",
           :address_1=>"Trzy Lipy", :address_2=>"20", 
           :postal=>"34-567",
           :city=>"Gdańsk", :country_code=>"PL"}, 
          {:selected_person=>true,
            :full_name=>"Fellow Fellow Last Name", :minor=>false}]

需求目标

统计output数组里,所有哈希元素中:selected_person值为true的次数。

当前尝试的两种方案

  • 方案A:总是返回2
    这段代码用了赋值运算符=,把每个哈希的:selected_person都强制设为true,赋值表达式的返回值就是true,所以不管原哈希中该键的值是什么,所有元素都会被计数:

    output.count { |h| h[:selected_person] = true }
    
  • 方案B:返回0
    执行下面的代码返回0,说明实际运行时,哈希里的:selected_person要么不存在,要么返回的是nil、false这类假值:

    output.count { |h| h[:selected_person]}
    

补充说明

保存时没注意到示例被修改,原关联问题里方案B是有效的,但本文里的output才是正确的测试代码。

正确解决方法

如果哈希里确实有:selected_person键且值为true,直接判断值严格等于true最稳妥(避免把1、非空字符串这类真值误算进去):

output.count { |h| h[:selected_person] == true }

要是确定:selected_person只有true、false或nil三种可能,也可以简化成:

output.count { |h| h[:selected_person] }

如果方案B返回0,先排查这几点:

  1. 键名是不是写错了?比如用了字符串"selected_person"而不是符号:selected_person;
  2. :selected_person的值是不是真的是布尔值true?别把字符串"true"当成布尔值;
  3. 数组里的元素是不是真的都是哈希,没嵌套其他类型的数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:39:18