I can count a value using Array#count
.
numbers = [1, 2, 5, 5, 1, 3, 1, 2, 4, 3]
numbers.count(1) #=> 3
How can I count multiple values in an array?
What I wrote were:
numbers.count(1) + numbers.count(2) #=> 5
[1,2].map{|i| numbers.count(i)}.sum #=> 5
I think these are a bit redundant.
To check if multiple values exist in an array:Use the every() method to iterate over the array of values. On each iteration, use the indexOf method to check if the value is contained in the other array. If all values exist in the array, the every method will return true .
You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.
Using sort function() Calculate the length of an array using the length() function that will return an integer value as per the elements in an array. Call the sort function and pass the array and the size of an array as a parameter. Take a temporary variable that will store the count of distinct elements.
count
can also take a block, so you can write this in a way that only traverses the array once:
numbers.count {|i| [1,2].include? i } # => 5
Or for fun, in a slightly more functional/point-free style:
numbers.count &[1,2].method(:include?) # => 5
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With