-4

I have complex hash which looks like this

 @hash =  {1=>[], 2=>[], 3=>[], 4=>[], 5=>[], 6=>[], 7=>[], 8=>[], 9=>[], 10=>[], 11=>[], 12=>[[{"value"=>1.58, "title"=>"sun", "quantity" => 2}], [{"value"=>1.99, "title"=>"sophia", "quantity" => 5}], [{"value"=>6.30, "title"=>"roam", "quantity" => 15}], [{"value"=>3.981, "title"=>"jia, "quantity" => 4"}], 13 => [], 14 => [], 15 => []}

now I want to extract highest value along with associated title and quantity. index would 15 all the time.

for example the output should be

@hash = { value => 6.30, title => "roam", quantity => 15 }

I was searhcing some found this but did not make it work reference link Ref

help appreciated thanks

Community
  • 1
  • 1
JNI_OnLoad
  • 5,472
  • 4
  • 35
  • 60
  • 2
    That hash isn't valid Ruby. – August Sep 03 '14 at 12:35
  • Maybe this: `@hash = { 1=>[], 2=>[], 3=>[], 4=>[], 5=>[], 6=>[], 7=>[], 8=>[], 9=>[], 10=>[], 11=>[], 12=>[[{"value"=>1.58, "title"=>"sun", "quantity" => 2}], [{"value"=>1.99, "title"=>"sophia", "quantity" => 5}], [{"value"=>6.30, "title"=>"roam", "quantity" => 15}], [{"value"=>3.981, "title"=>"jia", "quantity" => 4}]], 13 => [], 14 => [], 15 => []}` is you valid hash? – Surya Sep 03 '14 at 13:39

1 Answers1

1

If you're not interested in the element's index, you could flatten the values and find the maximum one:

@hash =  {
  1=>[], 2=>[], 3=>[], 4=>[], 5=>[], 6=>[], 7=>[], 8=>[], 9=>[],
  10=>[], 11=>[], 12=>[
    [{"value"=>1.58, "title"=>"sun", "quantity" => 2}],
    [{"value"=>1.99, "title"=>"sophia", "quantity" => 5}],
    [{"value"=>6.30, "title"=>"roam", "quantity" => 15}],
    [{"value"=>3.981, "title"=>"jia", "quantity" => "4"}]
  ],
  13 => [], 14 => [], 15 => []
}

@hash.values.flatten.max_by { |h| h["value"] }
#=> {"value"=>6.3, "title"=>"roam", "quantity"=>15}
Stefan
  • 109,145
  • 14
  • 143
  • 218