find the range of all values in a map in ruby

Assuming that you want to find the range of all the values in a Ruby hash (also known as a map), you can retrieve all the values of the hash using the values method, then use the min and max methods to find their minimum and maximum:

main.rb
hash = {a: 1, b: 2, c: 3}
values = hash.values
range = values.max - values.min
79 chars
4 lines

Alternatively, you can use the Enumerable module's minmax method to get an array of the minimum and maximum values, then calculate the range:

main.rb
hash = {a: 1, b: 2, c: 3}
values = hash.values
min_value, max_value = values.minmax
range = max_value - min_value
114 chars
5 lines

Both approaches will give you the range of all values in the hash.

related categories

gistlibby LogSnag