简体   繁体   English

如何从哈希数组中过滤出哈希?

[英]How do I filter out hashes from an array of hashes?

I have params that looks like this: 我有看起来像这样的params

params = [{:limit=>5}, {:skip=>0}, {:asc=>""}, {:desc=>""}]

I want to remove the hash elements whose value is 0 or an empty string. 我想删除值为0或空字符串的哈希元素。 I tried doing: 我试着做:

params.reject { |h| h.values !== 0 }

but this gives me a syntax error 但这给了我一个语法错误

Also tried: 还尝试了:

params.select { |h| h.values != 0 || h.values != "" }

but this gives me nothing. 但这什么也没给我。 What am I doing wrong? 我究竟做错了什么?

You have an array of hashes, so you have to operate on each hash. 您有一个哈希数组,因此必须对每个哈希进行运算。

params.reject { |hash| hash.any? { |_, v| [0, ''].include?(v) }}
#=> [{:limit=>5}]

Instead of having an array of hashes with only one pair of |key,value| 而不是仅具有一对|key,value|的哈希数组 , you could just merge all the hashes to get one big hash. ,您只需合并所有哈希即可获得一个大哈希。

It becomes easier to remove the unwanted values, and it also becomes easier to extract information : 删除不需要的值变得更加容易,并且提取信息也变得更加容易:

params = [{ limit: 5 }, { skip: 0 }, { asc: '' }, { desc: '' }]

hash = params.inject(&:merge).reject{|_, value| value == 0 || value == '' }
# => {:limit=>5}

hash[:limit]
# => 5

With an array of hashes, you'd have to write : 带有一系列哈希,您必须编写:

(h = array_of_hashes.find{|h| h.keys.include?(:limit)} ) && h[:limit]
#=> 5

I found two ways to do this: 我发现了两种方法可以做到这一点:

filtered = params.reject { |hash| hash.values.any? { |v| v.to_i == 0 } }

and

filtered = params.select { |hash| hash.values.none? { |val| val == '' || val == 0 } }

使用带有include的拒绝也将解决此问题。

 params.reject { |key| key.values.include?(0) || key.values.include?("") }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM