Hello, I have this orgy. How can I sort this miracle by "filter"?

ab = {"Кирпично-красный"=>[{"url"=>nil, "hex"=>"B10101", "filter"=>"Красный"}, ["000057233", "000022147"]] "Ярко-синий"=>[{"url"=>nil, "hex"=>"114C9C", "filter"=>"Синий"}, ["000040233", "000052147"]] "Клубнично-красный"=>[{"url"=>nil, "hex"=>"D10800", "filter"=>"Красный"} "Лаванда"=>[{"url"=>nil, "hex"=>"E6E6FA", "filter"=>"Синий"}, ["000033166"]] 

The result was that:

  ab = {"Кирпично-красный"=>[{"url"=>nil, "hex"=>"B10101", "filter"=>"Красный"}, ["000057233", "000022147"]] "Клубнично-красный"=>[{"url"=>nil, "hex"=>"D10800", "filter"=>"Красный"}, ["000047356", "000012891"] "Ярко-синий"=>[{"url"=>nil, "hex"=>"114C9C", "filter"=>"Синий"}, ["000040233", "000052147"]] "Лаванда"=>[{"url"=>nil, "hex"=>"E6E6FA", "filter"=>"Синий"}, ["000033166"]] 
  • I try to do it so ab.sort_by {| v, k | v [0] ["filter"]} But something does not come out - Litrein
  • I mean, sort? You do not have an array, but a hash. It is not intended to store a certain order (although it is capable of this). - D-side
  • I understand, but, unfortunately, I get such data. - Litrein
  • The point is not in the source data, but in what result you ultimately need. - D-side
  • This is a small piece of what is, filter is the color to which the key names belong (ie, the key may be Burgundy, but its parent is Red, ie, the filter), and it is the colors in the filter - Litrein that need to be arranged alphabetically

2 answers 2

ab.sort_by{|v, k| v[0]["filter"]} ab.sort_by{|v, k| v[0]["filter"]} does not work, because the order of k and v is confused. I guess sort

 ab.sort{|a, b| a[1][0]['filter'] <=> b[1][0]['filter']}.to_h 

will be faster in this case than sort_by

 ab.sort_by{|key,value| value[0]['filter']}.to_h 

If you are talking about a large amount of data, then make a benchmark just in case.

  • Swears, syntax error, unexpected ']', expecting => and syntax error, unexpected =>, expecting end-of-input - Litrein
  • @Litrein, you actually have syntax errors in the hash example, but I corrected them before trying it in the console - Vasilisa
  • Thanks, I probably, when Ctrl + C / V did messed up. - Litrein

Thanks to everyone, I learned how this miracle Yudo Hash is formed, the guy merzhil of two, in one

  {"Кирпично-красный"=>{"url"=>nil,"hex"=>"B10101","filter"=>"Красный"} 

In another

  {"Кирпично-красный"=>["000057233", "000022147"]]} 

In the end, sorted the first Hash, and smiled with the second, it turned out what I wanted