-
-
Save csquared/1485147 to your computer and use it in GitHub Desktop.
Inject vs. Readability
This file contains hidden or 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
# inject is cool and elegant. I use it when I want to be cool. However, I tend to robotically begin the procedural | |
# way and end up at inject when I realize I am in that situation. See this simple example: | |
include ActionView::Helpers | |
class Link < Struct.new(:title, :url); end | |
a = Link.new("Google", "http://www.google.com") | |
b = Link.new("Hacker News", "http://news.ycombinator.com") | |
array_of_links = [a, b] | |
# this is elegant and neat, but a headache to understand for newcomers | |
def the_cool_way(array_of_links) | |
array_of_links.inject(""){|output, link| output << link_to(link.title,link.url) } | |
end | |
# This is uncool procedural code, but almost anyone with programming experience | |
# can understand it. | |
def the_uncool_way(array_of_links) | |
output = "" | |
array_of_links.each do |link| | |
output << link_to(link.title, link.url) | |
end | |
# An explicit return? First of all, ew... | |
return output | |
end | |
##This is what happens when you see the above code and remember #tap before #inject | |
def the_tap_that_shit_way(array_of_links) | |
"".tap do |output| | |
array_of_links.each do |link| | |
output << link_to(link.title, link.url) | |
end | |
end | |
end | |
#i hope you're using matchit | |
# The result is the same. A code snob will look down their nose at you if you use | |
the_uncool_way the_cool_way(array_of_links) == the_uncool_way(array_of_links) | |
the_cool_way(array_of_links) == the_tap_that_shit_way(array_of_links) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment