1

Consider the below hash

[
{:rank => 3, :time => "3.00 AM" , :name => "JJJ"},
{:rank => 1, :time => "3.05 AM" , :name => "AAA"},
{:rank => 5, :time => "2.55 AM" , :name => "XXX"},
{:rank => 2, :time => "3.10 AM" , :name => "BBB"}
]

How do i sort the fields in an order, so that i will obtain result as like query
(Consider if we fetch values in has is from a table)

select * from my_table order by rank, time, name 

Please comment if i am not clear.

Thanks

1 Answer 1

5
a = [
{:rank => 3, :time => "3.00 AM" , :name => "JJJ"},
{:rank => 1, :time => "3.05 AM" , :name => "AAA"},
{:rank => 5, :time => "2.55 AM" , :name => "XXX"},
{:rank => 2, :time => "3.10 AM" , :name => "BBB"}
]
res = a.sort_by{|t| [t[:rank], t[:time], t[:name]]}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks izomorphius... as i am having time field as string, time sorting is not working.. any solution for this?
You could use the Chronic gem: res = a.sort_by{|t| [t[:rank], Chronic.parse(t[:time]), t[:name]]}
izomorphius thanks for the answer.. but what should i do to sort the time field in either direction.. if i tried to give like res = a.sort_by{|t| [t[:rank], -t[:time], t[:name]]} it throws an error!! any suggestions..?
@cometbalan a few suggestions can be found here: ruby-forum.com/topic/224672 I do not know of any really short way to do that.

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.