我有一个将用户请求作为json的类,如下所示:
json = { "val": { "a": 10, "b": 50, "c": 20, "d": 30, "e": 15 }
}
Run Code Online (Sandbox Code Playgroud)
并返回哈希值的最大值3:
例如:
它应该返回:
{
"b": 50
"d": 30
"c": 20
}
Run Code Online (Sandbox Code Playgroud)
这是我的方法:
require 'json'
module UserRequest
class << self
def call(json)
original = JSON.parse(json)
covers = original["covers"]
calculate_max(covers, 3)
end
def calculate_max(covers, max_num)
sorted = covers.sort_by { |k, v| v }
Hash[max_array(sorted, max_num)]
end
def max_array(array, max_num)
size = array.size
array.slice(size-max_num..last)
end
end
end
UserRequest.call(json)
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法可以做到这一点。请帮忙。应遵循SOLID红宝石原理
ruby ×1