5

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 so it would result in

id: 1,3,2

How can I sort this? I'm trying:

@people.sort! { |x,y| y[:fname] <=> x[:fname] }

But that has no effect.

1
  • 2
    That is not a JSON object. That is a Ruby array of hashes. Commented Feb 16, 2012 at 23:08

1 Answer 1

13

You can use sort_by.

@people.sort_by! { |x| x[:fname].downcase }

(the downcase is for the case insensitivity)

For completeness, the issues with the provided code are:

  • the arguments are in the wrong order
  • downcase is not being called

The following code works using the sort method.

@people.sort! { |x,y| x[:fname].downcase <=> y[:fname].downcase }

As proof 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.