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

如何筛选出哈希中值为非空数组的键并生成新哈希?

Ruby哈希过滤:保留值为非空数组的键值对

给定原哈希:

hash = {"lili" => [] , "john" => ["a", "b"], "andrew" => [], "megh" => ["b","e"]}

你可以用Ruby内置的Hash#select方法快速实现过滤,该方法会遍历哈希并保留满足条件的键值对:

方法一:判断数组是否非空

filtered_hash = hash.select { |key, value| !value.empty? }

方法二:更简洁的写法(利用数组any?方法)

如果数组包含至少一个元素,any?会返回true,写法更简洁:

filtered_hash = hash.select { |_, val| val.any? }

两种方法最终得到的结果都是:

{"john"=>["a", "b"], "megh"=>["b", "e"]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:30:42