Q:

How to get the next hash element from hash?

I have this hash:
HASH = {
  'x' => { :amount => 0 },
  'c' => { :amount => 5 },
  'q' => { :amount => 10 },
  'y' => { :amount => 20 },
  'n' => { :amount => 50 }    
}

How can I get the key with the next highest amount from the hash?
For example, if I supply x, it should return c. If there is no higher amount, then the key with the lowest amount should be returned. That means when I supply n, then x would be returned.
Can anybody help?

A:

I'd use something like this:
def next_higher(key)
  amount = HASH[key][:amount]
  sorted = HASH.sort_by { |_, v| v[:amount] }
  sorted.find(sorted.method(:first)) { |_, v| v[:amount] > amount }.first
end

next_higher "x" #=> "c"
next_higher "n" #=> "x"

