Get all keys in hash with same value

前端 未结 3 470
星月不相逢
星月不相逢 2021-01-07 12:32

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 sing

相关标签:
3条回答
  • 2021-01-07 13:13

    Or even better, yet simpler:

    h.select { |k,v| v == h.values.max }.keys
    

    For example,

    h = { "a" => 1, "b" => 2, "c" => 2 }
    # implement the above solution
    h.select { |k,v| v == h.values.max }.keys
        #=> ["b", "c"]
    

    Hopefully, that's what you'd want! :)

    0 讨论(0)
  • 2021-01-07 13:17

    I suggest you construct a hash rather than an array.

    h = { a: 1, b: 2, c: 1, d: 3, e: 2 }
    
    h.each_with_object({}) { |(k,v),g| (g[v] ||= []) << k }
      #=> {1=>[:a, :c], 2=>[:b, :e], 3=>[:d]} 
    

    This answers the question posed by the title of the question.

    0 讨论(0)
  • 2021-01-07 13:27

    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]})
    
    0 讨论(0)
提交回复
热议问题