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

Popular posts from this blog

delphi - blogger via idHTTP : error 400 bad request -

c++ - compiler errors when initializing EXPECT_CALL with function which has program_options::variables_map as parameter -

How do I check if an insert was successful with MySQLdb in Python? -