我在尝试对给定的价格和产品进行排序时遇到了一点问题。
arr = [[6,"iPhone"],[4,"Android"],[5,"iPhone"],[3,"Xbox"],
[9,"Android"],[8,"Xbox"]]
但我需要先按产品分类,然后按价格分类。我做了下一个常见的做法:
arr.sort_by! {|x| [x[1],x[0]]}.reverse
=> [[6, "iPhone"], [5, "iPhone"], [8, "Xbox"], [3, "Xbox"],
[9, "Android"], [4, "Android"]]
但是我现在需要再次按产品块对其进行排序,以首先获得最昂贵的一个块,依此类推。我正在寻找的结果如下:
arr = [[9,"Android"],[4,"Android"],[8,"Xbox"],[3,"Xbox"],
[6,"iPhone"],[5,"iPhone"]]
任何帮助将不胜感激!
更新 1 我已经测试了戴夫的答案及其作品,但在其他一组项目上,我没有得到正确的产品块。
arr = [[6.0,"iPad 2"], [7, "Mints"], [6.0, "Nerf Crossbow"], [4.5, "iPad 2"],
[6, "Mints"], [6.75, "Nerf Crossbow"], [6.0, "iPad 2"], [5, " Mints"],
[9.0, "Nerf Crossbow"]]
我得到了这个结果:
1.9.2p320 :5 > arr.sort! { |a, b| (a[1] <=> b[1]).nonzero? || b[0] <=> a[0] }
=> [[7, "Mints"], [6, " Mints"], [5, "Mints"], [9.0, "Nerf Crossbow"],
[6.75, "Nerf Crossbow"], [6.0, "Nerf Crossbow"], [6.0, "iPad 2"], [6.0, "iPad 2"],
[4.5, "iPad 2"]]
问题是我期待
[[9.0, "Nerf Crossbow"], [6.75, "Nerf Crossbow"], [6.0, "Nerf Crossbow"],
[7, "Mints"], [6, "Mints"], [5, "Mints"],[6.0, "iPad 2"], [6.0, "iPad 2"],
[4.5, "iPad 2"]]