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
enumthrough enumeration. If an argument is given, the number of items inenumthat are equal toitemare 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
				
                        
Sure it's possible. All you have to do is check if an argument is given and also check if a block is given.
Or:
The latter is useful because it converts the block to a Proc (named
block) that you can then reuse, as below.You could implement your own
countmethod like this:See it on repl.it: https://repl.it/@jrunning/YellowishPricklyPenguin-1