如何统计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,先排查这几点:
- 键名是不是写错了?比如用了字符串
"selected_person"而不是符号:selected_person; :selected_person的值是不是真的是布尔值true?别把字符串"true"当成布尔值;- 数组里的元素是不是真的都是哈希,没嵌套其他类型的数据。
内容的提问来源于stack exchange,提问作者user1128912
相关产品推荐
相关产品推荐

