Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Count Array objects if object includes value

Tags:

arrays

ruby

count

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.

like image 857
Luigi Avatar asked Dec 04 '13 21:12

Luigi


2 Answers

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/

like image 83
Paul Simpson Avatar answered Oct 20 '22 11:10

Paul Simpson


If you give a block to the count method of array, it iterates over the array and counts the values for which you return true:

array.count do |x|
  (x.downcase.include? 'footbal') || (x.downcase.include? 'baseball')
end
like image 40
Piotr Avatar answered Oct 20 '22 10:10

Piotr