cbutler cbutler - 1 year ago 140
Ruby Question

Ruby - 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

can anyone advise how to separate the keys so I end up with [["a"],["b"],["c"]] instead of [["a","b","c"]],

Answer Source

Maybe this?

h.select {|k, v| v == val}.keys.each {|k| @highest_wf_words << [k]}

Or this:

@highest_wf_words.concat(h.select {|k, v| v == val}.keys.map {|k| [k]})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download