我有以下哈希:
{
"day_mon"=>"on", "day_tue"=>"on", "day_wed"=>"on", "day_thu"=>"on",
"day_fri"=>"on", "day_sat"=>"on", "day_sun"=>"on"
}
如何计算散列中与字符串"day"
匹配的键数?
答案 0 :(得分:8)
无需创建临时数组:
h.count { |k,_| k.start_with?("day") }
#=> 7
我认为密钥必须以"day"
开头,但如果没有:
h.count { |k,_| k =~ /day/ }
#=> 7
答案 1 :(得分:4)
像这样:
h.keys.grep(/day/).count
编辑:因为Cary Swoveland完全正确,
h.each_key.lazy.grep(/day/).count
TIMTOWTDI:D
答案 2 :(得分:0)
hash
/day/
Array.count计算已过滤数组中元素的数量:
hash.keys.select { |key| key =~ /day/ }.count