获取哈希中具有相同值的所有键 [英] Get all keys in hash with same value
本文介绍了获取哈希中具有相同值的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从散列中获取具有相同值的所有键,并将它们作为单独的条目放入一个数组中.我有这行代码,但它将所有内容作为单个条目发送:
I am trying to get all the keys with the same value from a hash and put them into an array as separate entries. I have this line of code but it sends everything in as a single entry:
@highest_wf_words << h.select {|k, v| v == val}.keys
谁能建议如何分隔键,所以我最终得到 [["a"],["b"],["c"]] 而不是 [["a","b","c"]],
can anyone advise how to separate the keys so I end up with [["a"],["b"],["c"]] instead of [["a","b","c"]],
推荐答案
也许是这个?
h.select {|k, v| v == val}.keys.each {|k| @highest_wf_words << [k]}
或者这个:
@highest_wf_words.concat(h.select {|k, v| v == val}.keys.map {|k| [k]})
这篇关于获取哈希中具有相同值的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文