find the smallest key in a map in ruby

To find the smallest key in a Ruby Map (which is also known as Hash), you can use the built-in min method together with keys method, like this:

main.rb
my_map = { 'b' => 2, 'c' => 3, 'a' => 1 }

smallest_key = my_map.keys.min

puts smallest_key    # Output: "a"
110 chars
6 lines

In this example, we created a Map with three key-value pairs. To get the smallest key, we called the keys method on the map to get an array of all the keys, and then called the min method on the array to get the minimum value (which in this case is "a").

Note that this approach leverages Enumerable module which is included in Hash in Ruby.

gistlibby LogSnag