简体   繁体   中英

Sort two array of hashes by the same criteria on Ruby

I am working on Ruby with two arrays of hashes like these:

a = [{'name'=> 'Ana', 'age'=> 42 },
     {'name'=> 'Oscar', 'age'=> 22 },
     {'name'=> 'Dany', 'age'=> 12 }]

b = [{'name'=> 'Dany', 'country'=> 'Canada' },
     {'name'=> 'Oscar', 'country'=> 'Peru'},
     {'name'=> 'Ana', 'country'=>'France'}]

I am sorting them like this:

a.sort_by!{|c| c['name']}
b.sort_by!{|c| c['name']}

and it works, but since I doing the same on both arrays, I would like doing the same but in one line; I mean, sort the two arrays at once.

How can I do it?

Just put them in an array.

a = [{'name'=> 'Ana', 'age'=> 42 },
     {'name'=> 'Oscar', 'age'=> 22 },
     {'name'=> 'Dany', 'age'=> 12 }]

b = [{'name'=> 'Dany', 'country'=> 'Canada' },
     {'name'=> 'Oscar', 'country'=> 'Peru'},
     {'name'=> 'Ana', 'country'=>'France'}]

[a, b].each{|ar| ar.sort_by!{|c| c['name']}}
p b # => [{"name"=>"Ana", "country"=>"France"}, {"name"=>"Dany", "country"=>"Canada"}, {"name"=>"Oscar", "country"=>"Peru"}]

更简单的方法-

  a.zip(b).flatten.sort_by!{|c| c['name']})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM