Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Ruby Array Exercises: Find most occurred item in a given array

Ruby Array: Exercise-43 with Solution

Write a Ruby program to find most occurred item in a given array.

Ruby Array Exercises: Find most occurred item in a given array

Ruby Code:

nums = [10, 20, 30, 40, 10, 10, 20]
print "Original array:\n"
print nums
nums_freq = nums.inject(Hash.new(0)) { |h,v| h[v] += 1; h }
print "\nFrequency of numbers:\n"
print nums_freq

Output:

Original array:
[10, 20, 30, 40, 10, 10, 20]
Frequency of numbers:
{10=>3, 20=>2, 30=>1, 40=>1}

Flowchart:

Flowchart: Find most occurred item in a given array

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to convert an array into an index hash.
Next: Write a Ruby program to check whether all items are identical in a given array.

What is the difficulty level of this exercise?