Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform a complex custom sort in Ruby?

Tags:

sorting

ruby

I have an array that looks like the following:

[
  { type: 'A', price: '0.01' },
  { type: 'B', price: '4.23' },
  { type: 'D', price: '2.29' },
  { type: 'B', price: '3.38' },
  { type: 'C', price: '1.15' }
]

I need to group these by type and then sort them by ascending price. I can half solve this problem by doing the following:

boards.sort_by {|e| [e['type'], e['price'].to_f]}

Unfortunately, this sorts the types alphabetically when they should be sorted BADC

How do I sort the array by the pre-determined rules?

like image 856
purinkle Avatar asked Nov 14 '11 13:11

purinkle


1 Answers

ar=[
  { type: 'A', price: '0.01' },
  { type: 'B', price: '4.23' },
  { type: 'D', price: '2.29' },
  { type: 'B', price: '3.38' },
  { type: 'C', price: '1.15' }
]

SORT_ORDER = 'BADC' #could also be an array, eg ["monday", "tuesday", ...]
p ar.sort_by{|e| [SORT_ORDER.index(e[:type]), e[:price].to_f]}

Output:

[{:type=>"B", :price=>"3.38"},
 {:type=>"B", :price=>"4.23"},
 {:type=>"A", :price=>"0.01"},
 {:type=>"D", :price=>"2.29"},
 {:type=>"C", :price=>"1.15"}]
like image 121
steenslag Avatar answered Sep 19 '22 04:09

steenslag