find the minimum and maximum element in an array in Ruby
Code snippet on how to find the minimum and maximum element in an array in Ruby
numbers = [6, 2, 4, 8, 9]
min = numbers[0]
max = numbers[0]
numbers.each do |number|
min = number if number < min
max = number if number > max
end
puts "Min element: #{min}"
puts "Max element: #{max}"
This code finds the minimum and maximum values in the array called ‘numbers’. It starts with setting the min and max values to the first number in the array. It then loops through the array, checking each number against the min and max values. If the number is larger than the max value, it sets that number as the new max value. If the number is smaller than the min value, it sets that number as the new min value. After the loop is finished, it prints out the min and max values.