Sort array by values in a separate hash

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值