Reputation: 652
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?
Upvotes: 0
Views: 64
Reputation: 80065
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"}]
Upvotes: 2