简体   繁体   English

轻松找到具有特定值的所有哈希值

[英]Easy way to find all hashes with particular values

I have a following array of hashes 我有一系列哈希

h = [{:foo=>:bar}, {:qqq=>:ppp}, {:xxx=>123}]

I want to find all hashes which Symbol in values. 我想找到Symbol在值中的所有哈希值。

Currently I use this approach, but I don't actually like it because I have to create array for each hash and extract the first element ( hash.values[0] ). 目前我使用这种方法,但我实际上并不喜欢它,因为我必须为每个哈希创建数组并提取第一个元素( hash.values[0] )。

h.select { |hash| hash.values[0].is_a?(Symbol) }
# => [{:foo=>:bar}, {:qqq=>:ppp}]

Maybe there is something more elegant to do this? 也许有更优雅的东西可以做到这一点?

If you don't want to use array, use hash) 如果你不想使用数组,请使用hash)

h = { :foo=>:bar, :qqq=>:ppp, :xxx=>123 }
h.select { |k, v| v.is_a?(Symbol) }
=> { :foo=>:bar, :qqq=>:ppp }

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

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