Eki Eqbal
Eki Eqbal

Reputation: 6027

How to sort Ruby Hash based on date?

I have a hash object with the following structure:

{"action1"=>
  {"2014-08-20"=>0,
   "2014-07-26"=>1,
   "2014-07-31"=>1
  },
 "action2"=>
  {"2014-08-01"=>2,
   "2014-08-20"=>2,
   "2014-07-25"=>2,
   "2014-08-06"=>1,
   "2014-08-21"=>1
 }
 "action3"=>
  {"2014-07-30"=>2,
   "2014-07-31"=>1,
   "2014-07-22"=>1,
  }
}

I want to sort the hash based on the date and return back a Hash(Not array). The final result should be:

{"action1"=>
  {"2014-07-26"=>1,
   "2014-07-31"=>1,
   "2014-08-20"=>0
  },
 "action2"=>
  {"2014-07-25"=>2,
   "2014-08-01"=>2,
   "2014-08-06"=>2,
   "2014-08-20"=>1,
   "2014-08-21"=>1
 }
 "action3"=>
  {"2014-07-22"=>1,
   "2014-07-30"=>2,
   "2014-07-31"=>1
  }
}

Upvotes: 0

Views: 362

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

This is all you need:

h.each { |k,v| h[k] = v.sort.to_h }
  #=> {"action1"=>{"2014-07-26"=>1, "2014-07-31"=>1, "2014-08-20"=>0},
  #    "action2"=>{"2014-07-25"=>2, "2014-08-01"=>2, "2014-08-06"=>1,
  #       "2014-08-20"=>2, "2014-08-21"=>1},
  #    "action3"=>{"2014-07-22"=>1, "2014-07-30"=>2, "2014-07-31"=>1}}

Hash#to_h appeared in Ruby 2.0. For earlier versions, use the class method Hash::[]: i.e., replace v.sort.to_h with Hash[v.sort].

Upvotes: 1

SSP
SSP

Reputation: 2670

Here you need to iterate your hash and fetch the value than you need to apply sort_by function on each value so you will get your result

hashName.each do |key, hash|
  Hash[hashName.sort_by{|k,v| k}]
end

Upvotes: 1

Martin Konecny
Martin Konecny

Reputation: 59591

Iterate over the hash, and for each value, sort.

h = {"action1"=>
  {"2014-08-20"=>0,
   "2014-07-26"=>1,
   "2014-07-31"=>1
  },
 "action2"=>
  {"2014-08-01"=>2,
   "2014-08-20"=>2,
   "2014-07-25"=>2,
   "2014-08-06"=>1,
   "2014-08-21"=>1
 },
 "action3"=>
  {"2014-07-30"=>2,
   "2014-07-31"=>1,
   "2014-07-22"=>1,
  }
}

h.each do |k, v|
    h[k] = Hash[v.sort]
end

Upvotes: 3

Related Questions