Reputation: 2795
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"]
Upvotes: 1
Views: 51
Reputation: 303530
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
Upvotes: 2
Reputation: 118299
I'd do
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"]
Upvotes: 0