How do you sort an array of objects?
I have an object as follows:
[{:id=>2, :fname=>"Ron", :lname=>"XXXXX", :photo=>"XXX"}, {:id=>3, :fname=>"Dain", :lname=>"XXXX", :photo=>"XXXXXXX"}, {:id=>1, :fname=>"Bob", :lname=>"XXXXXX", :photo=>"XXXX"}]
I want to sort this by fname, alphabetically case insensitive, which will result in
id: 1,3,2
How can I sort this? I'm trying to:
@people.sort! { |x,y| y[:fname] <=> x[:fname] }
But this has no effect.
You can use sort_by .
@people.sort_by! { |x| x[:fname].downcase }
(lower case for case insensitive)
To complete the problem with the provided code:
- arguments are in the wrong order
- call down is not called
The following code works using the sort method.
@people.sort! { |x,y| x[:fname].downcase <=> y[:fname].downcase }
As evidence that both of these methods do the same thing:
@people.sort_by {|x| x[:fname].downcase} == @people.sort { |x,y| x[:fname].downcase <=> y[:fname].downcase }
Returns true .