happy coder
happy coder

Reputation: 19

sort an array in ascending and descending order by the hash keys of the containing elements in Ruby

The array is:

x= [{:dog=> :dog}, {:ant=> :ant}, {:cat=> :cat}]

I was wondering if anyone could explain how to do this and what the end result for both orders would look like.

Upvotes: 1

Views: 97

Answers (1)

ndnenkov
ndnenkov

Reputation: 36101

x.sort_by(&:keys)

x.sort do |first_hash, second_hash|
  second_hash.keys <=> first_hash.keys
end

You have an array of hashes with one element. In the ascending case, you can just say that you want to order by the keys of the hashes. It will default to alphabetic comparison.

For the descending case, you have to compare consecutive hashes with the <=> operator, which returns -1 if a<b, 0 in case of equality and 1 for a>b (given a <=> b). We just swap the places of a and b to get descending order.

Upvotes: 6

Related Questions