我有一个哈希映射数组索引来排序值,例如
{0=>"item_ss", 1=>"item_hsj", 2=>"item_skls"}
我有一个单独的数组line_item_id
和相关的line_items(制表符分隔),如下所示:
["item_skls \t sim1\t99\n", "item_ss \t sim2\t54\n", "item_hsj \t sim3\t48\n"]
如何使用散列值作为标识符和键作为数组的索引对数组进行排序?
例如,我希望上面的数组按如下方式排序:
["item_ss \t sim2\t99\n", "item_hsj \t sim3\t54\n", "item_skls \t sim1\t48\n"]
答案 0 :(得分:2)
a = ["item_skls \t sim1\t99\n", "item_ss \t sim2\t54\n", "item_hsj \t sim3\t48\n"]
h = {0=>"item_ss", 1=>"item_hsj", 2=>"item_skls"}
puts a.sort_by.with_index{ |v,i| h[i] }
#=> item_ss sim2 54
#=> item_hsj sim3 48
#=> item_skls sim1 99
答案 1 :(得分:0)
我会做
hash = {0=>"item_ss", 1=>"item_hsj", 2=>"item_skls"}
array = ["item_skls \t sim1\t99\n", "item_ss \t sim2\t54\n", "item_hsj \t sim3\t48\n"]
array.sort_by { |s| hash.find { |_,v| s.starts_with? v }.first }
# => ["item_ss \t sim2\t54\n",
# "item_hsj \t sim3\t48\n",
# "item_skls \t sim1\t99\n"]