0

I am trying sort Hash keys, (Keys can be duplicate) but Ruby is ignoring the duplicate Key and then sorting remaining keys with warning as below.

Code :

gridColumn1= Hash.new{|hsh,key| hsh[key] = [] }

gridColumn1 = { "z"=>["AAPL"], "A"=>["B"], "A"=>["AAPL", "FB", "GE"], "GOOG"=>["HD", "QQQ", "SCHW"], "V"=>[]}

gridColumn1.sort.to_h

Actual Output :

{"A"=>["AAPL", "FB", "GE"], "GOOG"=>["HD", "QQQ", "SCHW"], "V"=>[], "z"=>["AAPL"]}

with warning: duplicated key at line 14 ignored: "A"

I am expecting :

{"A"=>["B"], "A"=>["AAPL", "FB", "GE"], "GOOG"=>["HD", "QQQ", "SCHW"], "V"=>[], "z"=>["AAPL"]} 
Vasfed
  • 18,013
  • 10
  • 47
  • 53
Dave
  • 1
  • 3
  • Please read [the Hash documentation](http://ruby-doc.org/core-2.3.0/Hash.html): "`A Hash is a dictionary-like collection of unique keys and their values.`" You can't do what you are trying to do. – the Tin Man Mar 29 '16 at 18:16

1 Answers1

0

Ruby hash cannot have duplicate keys, it's whole purpose is to map key -> value.

To have duplicate keys - you can use an array of arrays:

gridColumn1 = [
  ["z", ["AAPL"]],
  ["A",["B"]],
  ["A",["AAPL", "FB", "GE"]],
  ["GOOG", ["HD", "QQQ", "SCHW"]],
  ["V", []]
]

gridColumn1.sort_by &:first
# => [["A", ["B"]], ["A", ["AAPL", "FB", "GE"]], ["GOOG", ["HD", "QQQ", "SCHW"]], ["V", []], ["z", ["AAPL"]]]
Vasfed
  • 18,013
  • 10
  • 47
  • 53
  • Thanks Vasfed, I can go with this approach but still I am getting out put as [["A", ["AAPL", "FB", "GE"]], ["A", ["B"]], ["GOOG", ["HD", "QQQ", "SCHW"]], ["V", []], ["z", ["AAPL"]]] but I am expecting [ ["A", ["B"]],["A", ["AAPL", "FB", "GE"]], ["GOOG", ["HD", "QQQ", "SCHW"]], ["V", []], ["z", ["AAPL"]]] . – Dave Mar 29 '16 at 17:43
  • @Dave that means you want to sort not only keys, but the value too, you can `.sort_by &:to_s` – Vasfed Mar 29 '16 at 19:27
  • No. gridColumn1 = [ ["Z"],["A", "K", "N"], ["A", "C"], ["A", "B"]] Say, I want to sort this 2 dimensional array on first element of each sub array and out put I am looking for is gridColumn1 = [ ["A", "K", "N"], ["A", "C"], ["A", "B"], ["Z"]]. Earlier I changed to Hashes as I was not getting above output using array but Hashes cant have duplicate keys, now I am back to the same problem. Thanks for your time. – Dave Mar 30 '16 at 05:40