Created
January 2, 2011 06:14
-
-
Save cwoodall/762340 to your computer and use it in GitHub Desktop.
Trying to explain blocks
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
## This file is not meant to run, just portray what Blocks do | |
## RUBY Example | |
names = ['Chris', 'Joe', 'Jeff', 'Tom'] | |
names.each do |name| | |
puts name | |
end | |
# OUTPUT: | |
# Chris | |
# Joe | |
# Jeffsdfas | |
# Tom | |
## Equivalent in python is: | |
names = ['Chris', 'Joe', 'Jeff', 'Tom'] | |
for name in names: print name | |
## | |
# In the case of the python version you are iterating through each element in the list. This is simple and | |
# straight forward. However in the ruby version what is happening is much harder to understand. The function | |
# each is a method of the list object names, which returns for each element in the list. In Ruby they call | |
# these enumerables, because they enumerate each item in a list (or range in the case of 5.times) | |
# For every time an element is "returned" it passes that element as the variable between the | |
# pipes (|variable|) to the block, which is basically just a function which isn't defined outside of the | |
# block (a super local function? or a lambda function). | |
# | |
# This is actually quite an elegant way to do things, but it can sometimes seem more like magic... | |
## |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Closures (what blocks really are)