find the range of a list of numbers in ruby

To find the range of a list of numbers in Ruby, you can use the minmax method provided by the Array class. The minmax method returns an array containing the minimum and maximum elements of the array. You can then construct a range object using these values.

Here's an example:

main.rb
nums = [2, 7, 1, 5, 10, 3]
range = nums.minmax.reduce(:..)
# => 1..10
70 chars
4 lines

In this example, we start with an array of numbers nums. We call the minmax method on the array to get an array of the minimum and maximum values. We use Ruby's reduce method to convert that array into a range object using the .. operator.

Now, range contains the range of the original list of numbers.

related categories

gistlibby LogSnag