开发者

Determine if a value exists in an array of hashes

开发者 https://www.devze.com 2022-12-08 03:45 出处:网络
I have the following: array_of_hashes = [{:a=>10, :b=>20}, {:a=>11, :b=>21}, {:a=>13, :b=>23}]

I have the following:

array_of_hashes = [{:a=>10, :b=>20}, {:a=>11, :b=>21}, {:a=>13, :b=>23}]

How would I go about findi开发者_高级运维ng if :a=>11 exists in array_of_hashes

array_of_hashes.include? does not seem to work


array_of_hashes.any? {|h| h[:a] == 11}


You did ask for a boolean result in the OQ, but if you really want the hash element itself do:

array_of_hashes.detect {  |h| h[:a] == 11 }

If you want the result really fast you could group the original object and then get the result with a single hash lookup:

t = array_of_hashes.group_by { |x| x[:a] }
t[11]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号