find the range of all elements in an array in ruby

To find the range of all elements in an array in Ruby, we can use the min and max methods of the Array object and combine them to create a Range object. Here's an example:

main.rb
array = [2, 6, 9, 3, 7, 1]
range = array.min..array.max

puts range # Output: 1..9
83 chars
5 lines

In this example, we first define an array of integers called array. Then, we use the min and max methods on the array object to find the smallest and largest element, respectively. Finally, we use the .. operator to create a Range object that includes all integers between the smallest and largest element of the array.

Note that if the array is empty, min and max will return nil, so you may want to add a condition to handle empty arrays differently.

related categories

gistlibby LogSnag