Ruby 新手,自己用 Ruby 实现了 Ruby 的Enumerable#inject
方法:Enumerable#my_inject
代码如下:
module Enumerable
def my_inject *arg
initial = method = nil
tmp = Array.new(self)
# 判断参数个数及类型
if arg.length > 2
raise ArgumentError, "wrong number of arguments #{arg.length} for 0..2"
elsif arg.length == 2
initial, method = arg[0], arg[1]
elsif arg.first.is_a? Symbol
method = arg.first
elsif arg.first
initial = arg.first
end
# 给accumulation赋值
accumulation = initial ? initial : tmp.shift
# 如果参数中有Symbol(方法)
if method
tmp.each do |element|
accumulation = accumulation.send(method, element)
end
else
tmp.each do |element|
accumulation = yield accumulation, element
end
end
accumulation
end
end
大家有兴趣的可以一起来讨论有没有更优雅的写法? 还有,我是新手,有经验的前辈可否指点一下我的代码?(思路、命名、注释..)