How to sort a ruby array by two conditions -


i want sort array 2 different conditionals.

first want sort array type: type can either (1,2,3,4) , want sort them in order 4 - 1 - 2 - 3.

then within each different type want sort them percentage descending.

so sorted array this:

[   <openstruct percent=70, type=4>,   <openstruct percent=60, type=4>,   <openstruct percent=50, type=4>,   <openstruct percent=73, type=1>,   <openstruct percent=64, type=1>,   <openstruct percent=74, type=2> ]ect 

how can accomplish sort? can sort type descending.

array = array.sort_by {|r| r.type } 

this should it:

require 'ostruct' arr = [   openstruct.new(percent: 73, type: 1),   openstruct.new(percent: 70, type: 4),   openstruct.new(percent: 60, type: 4),   openstruct.new(percent: 50, type: 4),   openstruct.new(percent: 64, type: 1),   openstruct.new(percent: 74, type: 2) ]   puts arr.sort_by { |a| [a.type % 4, -a.percent] } 

output:

#<openstruct percent=70, type=4> #<openstruct percent=60, type=4> #<openstruct percent=50, type=4> #<openstruct percent=73, type=1> #<openstruct percent=64, type=1> #<openstruct percent=74, type=2> 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -