find the largest key in a map in ruby

To find the largest key in a Ruby hash (which is equivalent to a map in other languages), you can use the max method with a block that compares the keys. Here's an example:

main.rb
my_hash = { "foo" => 1, "bar" => 2, "baz" => 3 }

largest_key = my_hash.keys.max {|a,b| a <=> b}

puts largest_key # Output: "foo"
131 chars
6 lines

In this example, we first create a hash called my_hash with three key-value pairs. Then, we use the keys method to get an array of all the keys in the hash, and pass it to the max method with a block. The block compares two keys a and b using the spaceship operator <=>, which returns -1, 0, or 1 depending on whether a is less than, equal to, or greater than b.

The max method returns the largest key according to the block, which we assign to largest_key. Finally, we print out the value of largest_key, which in this case is "foo".

related categories

gistlibby LogSnag