Sorting: Sort array based on multiple conditions in Ruby -
Sorting: Sort array based on multiple conditions in Ruby -
i have mulitdimensional array so:
[ [name, age, date, gender] [name, age, date, gender] [..] ] i'm wondering best way sort array based on multiple conditions...for instance, how sort based on age first name?
i messing around sort method so:
array.sort { |a,b| [ a[1], a[0] ] <=> [ b[1], b[0] ] } besides don't understand syntax, i'm not getting results expect. should using sort method? should individually comparing results mapping array?
you should always utilize sort_by keyed sort. not much more readable, much more efficient. in addition, prefer utilize destructuring bind, again, readability:
ary.sort_by {|name, age| [age, name] } ruby arrays sorting
Comments
Post a Comment