I'v a hash
{1=>true, 7=>false, 6=>true, 4=>false}
or an array like
[1, true], [7, false], [6, true], [4, false]]
or
[true, false, true, false]
.
How can I find the number of true
s in the array?
The frequency of an element can be counted using two loops. One loop will be used to select an element from an array, and another loop will be used to compare the selected element with the rest of the array. Initialize count to 1 in the first loop to maintain a count of each element.
Array#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array. Syntax: Array. count() Parameter: obj - specific element to found Return: removes all the nil values from the array.
Ruby | Array class last() function last() is a Array class method which returns the last element of the array or the last 'n' elements from the array.
Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.
In order to count the elements, you obviously have to iterate over the collection. Since iterating over a Hash
yields two-element Array
s, the first two are actually exactly the same:
{ 1 => true, 7 => false, 6 => true, 4 => false }.count(&:last)
[[1, true], [7, false], [6, true], [4, false]].count(&:last)
For the simple Array
case, you could do something like this:
[true, false, true, false].count(true)
This Array
is of course also the same as the Hash#values
from your Hash
above, so you could use the same method on that:
{ 1 => true, 7 => false, 6 => true, 4 => false }.values.count(true)
If you don't know which one of three you will get, you could use something like this:
{ 1 => true, 7 => false, 6 => true, 4 => false }.flatten.count(true)
[[1, true], [7, false], [6, true], [4, false]].flatten.count(true)
[true, false, true, false].flatten.count(true)
With Enumerable#count:
hash.values.count(true)
array_of_pairs.map { |k, v| v }.count(true)
plain_array.count(true)
More verbose, but does not create intermediate arrays:
hash_or_array_of_pairs.inject(0) { |acc, (k, v)| acc + (v == true ? 1 : 0) }
Simpler:
hash.values.count(true)
array.flatten.count(true)
This works with all the above cases.
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