Skip to content

Instantly share code, notes, and snippets.

@subvertallchris
Last active August 29, 2015 14:06
Show Gist options
  • Save subvertallchris/1d1bb3f988f12afd6ab6 to your computer and use it in GitHub Desktop.
Save subvertallchris/1d1bb3f988f12afd6ab6 to your computer and use it in GitHub Desktop.
my_inject refactored for /u/zaclacgit
def my_inject(initial = nil, sym = nil)
memo, starter = initial, self if initial && block_given?
memo, starter = self[0], self[1..-1] if initial.nil? || !block_given?
starter.push(initial) unless sym.nil? || block_given?
starter.my_each do |x|
if sym
memo = memo.send(sym, x)
elsif block_given?
memo = yield(memo,x)
else
memo = memo.send(initial, x)
end
end
memo
end
# OR
def my_inject(initial = nil, sym = nil)
if initial && block_given?
memo, starter = initial, self
else
memo, starter = self[0], self[1..-1]
end
starter.push(initial) unless sym.nil? || block_given?
starter.my_each do |x|
if sym
memo = memo.send(sym, x)
elsif block_given?
memo = yield(memo,x)
else
memo = memo.send(initial, x)
end
end
memo
end
@subvertallchris
Copy link
Author

the only difference between these two is the use of five lines for the leading if statement VS 2. The second one makes it clear that this is an either/or scenario but it's a bit longer, so it's really up to you to decide which you're looking for. Generally, the more readable solution is better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment