Ruby Basic Exercises: Count the number of 5's in a given array
Write a Ruby program to 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:
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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics