ruby - How to get the next hash element from hash? -
i have hash:
hash = { 'x' => { :amount => 0 }, 'c' => { :amount => 5 }, 'q' => { :amount => 10 }, 'y' => { :amount => 20 }, 'n' => { :amount => 50 } }
how can key next highest amount
hash?
for example, if supply x
, should return c
. if there no higher amount, key lowest amount should returned. means when supply n
, x
returned.
can help?
i'd use 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"