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.rb83 chars5 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.
gistlibby LogSnag