Trying to get a value out of 2d array inside of a hash and determine its max or min value
This is what I have so far
pretend_hash = { 333 => [Dog,19.99], 222=> [Cat,25.55] }
if a == 5 # Loop for view highest priced product"
puts "View highest priced product"
puts pretend_hash.values.max
end
So this returns the highest alphabetical value in the first part of the array by default Which would be Dog. How do I go about getting access to the 2nd part of the array w开发者_如何转开发here 25.55 gets declared the .max value? Something like pretend_hash.values.max[|k,v,z| print z] or a reverse on something?
The other problem I'm having is iterating through 2nd hash elements and determining the sum. Again callling that 2nd element in the array is something I'm not able to find the syntax for. I mean its not hard to say 19.99+25.55 = some variable and slam it into a puts. I'm assuming its something like:
pretend_hash.sum{|k,v,z| ?? }
#I assume it iterates through the z element
#and adds all current z values and returns the sum?
Min/max can be solved like this:
pretend_hash.values.sort{|x,y| x[1] <=> y[1]}[0] # Gives min, -1 will be max
Or:
pretend_hash.values.map{|x| x[1]}.max
And sum can be had like this:
pretend_hash.values.inject(0){|sum,x| sum+x[1]}
pretend_hash = { 333 => ["Dog",19.99], 222=> ["Cat",25.55] }
key,value = pretend_hash.max{|a,b| b[1] <=> a[1]}
puts key.to_s
puts value.join(',')
puts pretend_hash.inject(0){|sum, hash| sum + hash[1][1]}.to_s
#returns:
#222
#Cat,25.55
#45.54
精彩评论