w3resource

Ruby Array Exercises: Get the number of even integers in a given array

Ruby Array: Exercise-29 with Solution

Write a Ruby program to get the number of even integers in a given array.

Ruby Array Exercises: Get the number of even integers in a given array

Ruby Code:

def check_array(nums)
  count = 0    
  nums.each do |item|
    if((item % 2) == 0)
	count=count + 1
    end 
  end   
  return count
end
print check_array([3, 4, 5, 6]),"\n"
print check_array([3, 4, 5]),"\n"
print check_array([3, 4]) 

Output:

2
1
1

Flowchart:

Flowchart: Get the number of even integers in an given array

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to create a new array with the first element of two arrays. If lenght of any array is 0, ignore that array.
Next: 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.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.