Q: Ruby iterate through hash and compare value pairs My Ruby assignment is to iterate through a hash and return the key associated with the lowest value, without using any of the following methods:
#keys #values #min #sort #min_by

I don't understand how to iterate through the hash and store each pair as it comes through, compare it to the last pair that came through, and return the lowest key.  This is my code to show you my thought process, but it of course does not work.  Any thoughts on how to do this? Thanks!
def key_for_min_value(name_hash)
  index = 0 
  lowest_hash = {}

  name_hash.collect do |key, value|
    if value[index] < value[index + 1]
      lowest = value
      index = index + 1 
      key_for_min_value[value]

      return lowest
    end
  end
end 


A: Track min_value and key_for_min_value. Iterate through the hash, and any time the current value is lower than min_value, update both of these vars. At the end of the loop, return key_for_min_value.
I didn't include sample code because, hey, this is homework. :) Good luck!

A: One way to do it is transforming our hash into an array;
def key_for_min_value(name_hash)
  # Convert hash to array
  name_a = name_hash.to_a

  # Default key value
  d_value= 1000
  d_key= 0

  # Iterate new array 
  name_a.each do |i|
      # If current value is lower than default, change value&key 
      if i[1] < d_value
        d_value = i[1]
        d_key = i[0]
      end

   end

  return d_key

end  

You might need to change d_value to something higher or find something more creative :)

A: We can use Enumerable#reduce method to compare entries and pick the smallest value. Each hash entry gets passed in as an array with 2 elements in reduce method, hence, I am using Array#first and Array#last methods to access key and values.
h = {"a" => 1, "b" => 2, "c" => 0}
p h.reduce{ |f, s| f.last > s.last ? s : f }.first
#=> "c"

