Ruby Array Exercises: Compute the average values of a given array of except the largest and smallest values
Ruby Array: Exercise-31 with Solution
Write a Ruby program to compute the average values of a given array, except the largest and smallest values. The array length must be 3 or more.
Ruby Code:
def check_array(nums)
min = nums[0]
max = nums[0]
sum = 0
nums.each do |item|
sum = sum + item
if(item > max)
max = item
elsif(item < min)
min = item
end
end
return (sum-max-min).to_f/(nums.length - 2)
end
print check_array([3, 4, 5, 6]),"\n"
print check_array([12, 3, 7, 6]),"\n"
print check_array([2, 15, 7, 2]),"\n"
print check_array([2, 15, 7])
Output:
4.5 6.5 4.5 7.0
Flowchart:
Ruby Code Editor:
Contribute your code and comments through Disqus.
Previous: 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.
Next: Write a Ruby program to compute the sum of the numbers of a given array except the number 17 and numbers that come immediately after a 17. Return 0 for an empty array.
What is the difficulty level of this exercise?
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://w3resource.com/ruby-exercises/array/ruby-array-exercise-31.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics