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" 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -