So, I'm going through The Odin Project's Ruby Path, and in one of the Projects we have to rewrite some of the Enum
functions to their basic functionality. Thing is, I want to try to go beyond and recreate those functions as close to the original ones as possible, which brings me to Enum#inject
.
I have recreated it using the following code (which is inside the Enumerable
module)
def my_inject(initial = first, sym = nil)
memo = initial
enum = to_a
if block_given?
enum.my_each_with_index do |el, idx|
next if memo == first && idx.zero?
memo = yield memo, el
end
else
block = sym.to_proc
enum.my_each_with_index do |el, idx|
next if memo == first && idx.zero?
memo = block.call memo, el
end
end
memo
end
(my_each_with_index
being a custom version of each_with_index
that should work like so)
This version is almost working fine. Problem is only when I call it with only a Symbol
as argument, like in ((5..10).my_inject(:+))
, cause it throws a 'my_inject': undefined method 'to_proc' for nil:NilClass (NoMethodError)
.
I'm guessing this is happening because the symbol is being passed as the initial
value, as the first parameter of the function.
I thought about trying to write a bunch of checks (like to check if the function has only one argument and that argument is a symbol), but I wanna know if there is an easier and cleaner way of doing it so.
(Please, bear in mind I've been studying code for no more than 6 months, so I am a very very VERY green at this).
I appreciate the help!