Last active
August 29, 2015 14:06
-
-
Save subvertallchris/1d1bb3f988f12afd6ab6 to your computer and use it in GitHub Desktop.
my_inject refactored for /u/zaclacgit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.