You mean something pretty like this?
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4].count_all(3, 4) # => 7
While there's nothing in Ruby's core library that provides that functionality directly, it's pretty trivial to add it.
You could just write helper method:
def count_all(array, values_to_count)
array.count { |el| values_to_count.include?(el) }
end
count_all([1, 2, 2, 3, 3, 3, 4, 4, 4, 4], [3, 4]) # => 7
You could instead use Ruby's new refinements to add a method to Array
when you need it:
module ArrayExtensions
refine Array do
def count_all(*values_to_count)
self.count { |el| values_to_count.include?(el) }
end
end
end
# Then inside some module or class
using ArrayExtensions
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4].count_all(3, 4) # => 7
Or you could opt to take the more hacky path and modify Array
directly:
class Array
def count_all(*values_to_count)
self.count { |el| values_to_count.include?(el) }
end
end
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4].count_all(3, 4) # => 7