Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate highest maximum 3 values in hash

Tags:

ruby

I have a class which will take user request as json shown below:

   json = { "val": { "a": 10, "b": 50, "c": 20, "d": 30, "e": 15 } 
   }

and return max 3 of hash value:

for eg:

It should return:


{
"b": 50
"d": 30
"c": 20
}

This is my approach:


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)

Is there any better way to do this. Please help. Should follow SOLID ruby principles

like image 564
max mitch Avatar asked Jan 22 '26 20:01

max mitch


2 Answers

This should work

  module UserRequest
    class << self
      def call(json:, key: 'val', limit: 3)
        json[key].max_by(limit){|_,v| v}.to_h
      end
    end
  end
like image 56
user6500179 Avatar answered Jan 25 '26 13:01

user6500179


Other option, given the input json:

json = "{\"val1\":{\"a\":10,\"b\":50,\"c\":20,\"d\":30,\"e\":15}, \"val2\":{\"z\":100,\"x\":50,\"w\":200,\"y\":30,\"v\":150}}"

You could sort on the fly while parsing to Hash, this applies to any key:

require 'json'
h = JSON.parse(json).transform_values { |v| v.sort_by { |_, v| -v } }

So you can define some methods in your class or module:

h['val1'].first(3).to_h #=> {"b"=>50, "d"=>30, "c"=>20}
h['val2'].last(3).to_h #=> {"z"=>100, "x"=>50, "y"=>30}

Or use to_json instead of to_h.

like image 28
iGian Avatar answered Jan 25 '26 11:01

iGian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!