Ilya Cherevkov
Ilya Cherevkov

Reputation: 1803

Sort hash by key in descending order

I have the following hash:

{"2013-08-12"=> 10, "2013-08-13"=> 20, "2013-11-11"=>30, "2013-11-14"=> 40} 

What I want to do is to sort it by key (dates in format yyyy-mm-dd) in descending order:

{"2013-11-14"=> 40, "2013-11-11"=>30, "2013-08-13"=> 20, "2013-08-12"=> 10} 

Is this possible?

Upvotes: 0

Views: 3059

Answers (1)

sawa
sawa

Reputation: 168269

It is possible.

Hash[
  {"2013-08-12"=> 10, "2013-08-13"=> 20, "2013-11-11"=>30, "2013-11-14"=> 40}
  .sort_by{|k, _| k}.reverse
]

# => {
  "2013-11-14" => 40,
  "2013-11-11" => 30,
  "2013-08-13" => 20,
  "2013-08-12" => 10
}

Upvotes: 3

Related Questions