Ruby Count Array objects if object includes value

arrays, count, ruby

Solution

I would use `count` combined with a block that checks each element against a regular expression that matches the constraints you're looking for. In this case:

array.count { |element| element.match(/(football|baseball)s?\Z/i) }

This will match any of these elements: football, footballs, baseball, baseballs.

The `s?` makes the 's' optional, the `i` option (`/i`) makes the expression case insensitive, and the `\Z` option checks for the end of the string.

You can read more about Regexps in the Ruby docs: http://www.ruby-doc.org/core-2.0.0/Regexp.html

A great tool for playing with Regexps is Rubular: http://rubular.com/

Problem

I have an array: ``` array = ['Footballs','Baseball','football','Soccer'] ``` and I need to count the number of times Football or Baseball is seen, regardless of case and pluralization. This is what I tried to do, but with no luck: ``` array.count { |x| x.downcase.include? 'football' || x.downcase.include? 'baseball' } ``` What is a right or better way to write this code? I am looking for 3 as an answer.

Original source