find the smallest value in a map in ruby

To find the smallest value in a map (hash) in Ruby, we need to iterate over the values of the hash and compare each value with the current smallest value.

main.rb
map = {a: 4, b: 2, c: 10, d: 5}
smallest_value = nil

map.each_value do |value|
  if smallest_value.nil? || value < smallest_value
    smallest_value = value
  end
end

puts smallest_value # outputs 2
201 chars
11 lines

In this example, we first initialize the smallest_value variable to nil. This is because we don't know the initial smallest value, so we start with no value.

We then use the each_value method to iterate over each value in the hash. For each value, we check it against the current smallest_value. If the smallest_value is nil or the current value is smaller than smallest_value, we update smallest_value to the current value.

After iterating over all values, smallest_value will contain the smallest value in the map.

related categories

gistlibby LogSnag