Fellow Stranger Fellow Stranger - 4 months ago 7
Ruby Question

Order Hash and delete first key-value pair

I have a Hash with timestamp as keys.

hash = {
"2016-05-31T22:30:58+02:00" => {
"path" => "/",
"method" => "GET"
"2016-05-31T22:31:23+02:00" => {
"path" => "/tour",
"method" => "GET"
"2016-05-31T22:31:05+02:00" => {
"path" => "/contact_us",
"method" => "GET"

I order the collection and get the first pair like this:

hash.sort_by {|k, _| k}.first.first

But how do I remove it?

method requires you to know the exakt spelling of the key. Of course I could return the key and then use it in the
method, but I was thinking if there was any more straight forward way?


The method you are looking for is hash.keys it returns an array of the keys:


EDIT: I've updated the answer to reflect that keys must be sorted first, this has been added in the original question and brought up by @Shadwell in comments to this post.

I replaced hash.keys.sort.first for hash.keys.min as suggested by @Cary Swoveland, it is not only more performant but better semantically.