[Ruby] How to count even or odd numbers in an array

Create a method that counts even or odd numbers of values in the array.

Use the even? </ Font> method if the value is even, and the odd? </ Font> method if the value is odd.

  • Only even-numbered patterns are listed below. It can be used for odd counts by converting even to odd.

Example of use

Ruby


number = 2
number.even?

//→ true is returned

Answer example

Ruby


def count(number)
  count = 0
  number.each do |num|
    if num.even?
      count += 1
    end
  end
  puts count
end

Commentary

This time, in order to create a method, the method name and the formal argument number are described on the first line.

Ruby


def count(number)

As mentioned above, the even? Method returns only true or false, so it cannot be counted by itself. Therefore, if you use the even? Method on an array as shown below, an error will occur.

Failure example

Ruby


hairetsu = [1,2,6,8,10]
hairetsu.even?

// NoMethodError (undefined method `even?' for [1, 2, 6, 8, 10]:Array)

In addition, although count = o is described in the second line, the count is initialized by describing it before the iterative processing.

In order to count, iterate by the each method. As a flow, if it is true, it counts up, and if it is false, it does nothing and proceeds to the judgment of the next element.

Ruby


number.each do |num|
  if num.even?
    count += 1
  end
end

I'm using the puts method to output what I counted last.

Ruby


puts "count"

You have now created an even or odd counting method in a generic array. When calling the method, don't forget to specify the array as the actual argument from outside the method.

Recommended Posts