w3resource

Ruby Basic Exercises: Count the number of 5's in a given array

Ruby Basic: Exercise-41 with Solution

Write a Ruby program to count the number of 5's in a given array.

Ruby Basic Exercises: Count the number of 5's in a given array

Ruby Code:

def array_count(array)
   count = 0
    array.each{|item| count += 1 unless item != 5}
    return count
end

print array_count([1, 2, 9]),"\n"
print array_count([1, 2, 5, 9]),"\n"
print array_count([1, 2, 5, 9, 5])

Output:

0
1
2

Flowchart:

Flowchart: Count the number of 5's in a given array

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to create a new string taking every other character starting with the first of a given string.
Next: Write a Ruby program to check if one of the first 5 elements in a given array of integers is a 7. The array length may be less than 5.

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://w3resource.com/ruby-exercises/basic/ruby-basic-exercise-41.php