Skip to content

Instantly share code, notes, and snippets.

@cwoodall
Created January 2, 2011 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwoodall/762340 to your computer and use it in GitHub Desktop.
Save cwoodall/762340 to your computer and use it in GitHub Desktop.
Trying to explain blocks
## 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...
##
@cwoodall
Copy link
Author

cwoodall commented Jan 2, 2011

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