Created
October 31, 2017 21:12
-
-
Save rivertam/a9939bb52a0ac1a94e34e40b3ac49567 to your computer and use it in GitHub Desktop.
What is reduce?
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
arr = ["cup", "cake", "birthday", "Jesus"] | |
# this will print "cup\ncake\nbirthday\nJesus", as you can imagine | |
for word in arr | |
puts word | |
end | |
def add_em_up() | |
acc = 5 | |
for word in arr | |
acc = acc + word.length | |
end | |
acc # returns acc from add_em_up | |
end | |
def reduce_em() | |
# acc starts as 5 because it's the first parameter (usually called "initial" or similar) | |
# it is *always* a number | |
arr.reduce 5 do |acc, word| # word is each word; this do block gets called for each one | |
acc + word.length # implicitly return the addition from the do loop | |
end # because the reduction is the last value in the function, its return value is implicitly returned from reduce_em | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment