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"]} 
1
  • Please read the Hash documentation: "A Hash is a dictionary-like collection of unique keys and their values." You can't do what you are trying to do. Commented Mar 29, 2016 at 18:16

1 Answer 1

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"]]]
Sign up to request clarification or add additional context in comments.

3 Comments

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 that means you want to sort not only keys, but the value too, you can .sort_by &:to_s
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.