w3resource

Ruby Array Exercises: Find the difference between the largest and smallest values of a given array of integers of length 1 or more

Ruby Array: Exercise-30 with Solution

Write a Ruby program to find the difference between the largest and smallest values of a given array of integers of length 1 or more.

Ruby Array Exercises: Find the difference between the largest and smallest values of a given array of integers of length 1 or more

Ruby Code:

def check_array(nums)
  max = nums[0];
  min = nums[0];
  nums.each do |item|
    if(item > max)
			max = item;
		elsif(item < min)
			min = item
    end 
   end    
  return (max-min)
end

print check_array([3, 4, 5, 6]),"\n"
print check_array([3, 4, 5]),"\n"
print check_array([3, 4])

Output:

3
2
1

Flowchart:

Flowchart: Find the difference between the largest and smallest values of an given array of integers and length 1 or more

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to get the number of even integers in a given array.
Next: Write a Ruby program to compute the average values of an given array, except the largest and smallest values. The array length must be 3 or more.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/ruby-exercises/array/ruby-array-exercise-30.php