您的位置:首页 > 产品设计 > UI/UE

Sort array by values in a separate hash

2014-06-27 09:18 309 查看
I have a hash mapping array indices to sort values, e.g.
{0=>"item_ss", 1=>"item_hsj", 2=>"item_skls"}


I have a separate array with 
line_item_id
 and
associated line_items (tab separated) as follows:
["item_skls \t sim1\t99\n", "item_ss \t sim2\t54\n", "item_hsj \t sim3\t48\n"]


How can I sort the array using the values of the hash as the identifier and the key as the index of for the array?

For example, I want the array above to be sorted as follows:

["item_ss
\t sim2\t99\n","item_hsj
\t sim3\t54\n","item_skls
\t sim1\t48\n"]



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] }

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.start_with? v }.first }
# => ["item_ss \t sim2\t54\n",
#     "item_hsj \t sim3\t48\n",
#     "item_skls \t sim1\t99\n"]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: