End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#tally
tally → new_hash
tally(hash) → hash
enum.c
View on GitHub ↗
static VALUE
enum_tally(int argc, VALUE *argv, VALUE obj)
{
VALUE hash;
if (rb_check_arity(argc, 0, 1)) {
hash = rb_to_hash_type(argv[0]);
rb_check_frozen(hash);
}
else {
hash = rb_hash_new();
}
return enum_hashify_into(obj, 0, 0, tally_i, hash);
}
Returns a hash containing the counts of equal elements:
-
Each key is an element of
self. -
Each value is the number elements equal to that key.
With no argument:
Example
%w[a b c b c a c b].tally # => {"a"=>2, "b"=>3, "c"=>3}
With a hash argument, that hash is used for the tally (instead of a new hash), and is returned; this may be useful for accumulating tallies across multiple enumerables:
Example
hash = {} hash = %w[a c d b c a].tally(hash) hash # => {"a"=>2, "c"=>2, "d"=>1, "b"=>1} hash = %w[b a z].tally(hash) hash # => {"a"=>3, "c"=>2, "d"=>1, "b"=>2, "z"=>1} hash = %w[b a m].tally(hash) hash # => {"a"=>4, "c"=>2, "d"=>1, "b"=>3, "z"=>1, "m"=> 1}
Ruby version changes
-
3.1
-
Enumerable#tallynow accepts an optional hash to count. [Feature #17744]
-