I'm doing the lessons on The Odin Project and now I have to write myself a new #count
method (with another name) that behaves like the normal one from the Enumerable module.
The documentation on count says the following (http://ruby-doc.org/core-2.4.0/Enumerable.html#method-i-count):
count → int
count(item) → int
count { |obj| block } → intReturns the number of items in
enum
through enumeration. If an argument is given, the number of items inenum
that are equal toitem
are counted. If a block is given, it counts the number of elements yielding a true value.
I think I can write all of these as separate methods, but I was mostly wondering if one method definition can combine the last two uses of count
- with item
and with the block. Naturally, I'm wondering if all three can be combined in one definition, but I'm mostly interested in the last two. So far I can't seem to find a possible answer.
The documentation page has these examples:
ary = [1, 2, 4, 2]
ary.count #=> 4
ary.count(2) #=> 2
ary.count{ |x| x%2==0 } #=> 3