Skip to content

Instantly share code, notes, and snippets.

@SandNerd
Forked from Jauny/gist:3876531
Created August 12, 2016 22:35
Show Gist options
  • Save SandNerd/10a1b2d3f025cbc18e2bfaa94908fe84 to your computer and use it in GitHub Desktop.
Save SandNerd/10a1b2d3f025cbc18e2bfaa94908fe84 to your computer and use it in GitHub Desktop.
Understanding blocks, Procs and lambda!

#Understanding blocks, Procs and lambdas. I think blocks, Procs and lambdas are working in a really counter-intuitive way when you
first try to understand how they work, and most of the (amazing) resources one can find online
are too complicated to allow to understand how they work without frustration...

So here is my take on it; I'll try to make it as simple and concise as possible,
and will focus on how it is used, instead of how it works under the hood.

##Blocks A block is simply a piece of code that will (usually) execute something; Every time you write do... end or { ... }, it means you are writing a block.

##Procs A Proc is a class in which you can create a block, allowing you to save a block into a variable.

my_proc = Proc.new { puts "Hi! I'm a proc!" }
my_proc.call
=> "Hi! I'm a proc!"

##Lambdas Lambdas are a kind of block, but not Procs, so can't be saved.
They also offer 2 different behaviours compared to blocks;

_ First, they CARE about the arguments;

def method(code)
  one, two = 1, 2
  code.call(one, two)
end

method( lambda { |a, b, c| puts "#{a}, #{b}, #{c}" } )
=> ArgumentError: wrong number of arguments (2 for 3)

method( Proc.new { |a, b, c| puts "#{a}, #{b}, #{c}" } )
=> 1, 2, 

_ Second, whatever they return, they will let the method calling them continue,
while Procs just stops the method, forbidding anything after them to execute.

def proc_return
  Proc.new { return "Proc.new"}.call
  return "proc_return method finished"
end
=> Proc.new

def lambda_return
  lambda { return "lambda" }.call
  return "lambda_return method finished"
end
=> lambda_return method finished

##Conclusion We have, in fact, 2 things;
blocks, coming from the class Procs, which are only parts of code.
And lambdas, a kind of block, but not from the class Proc.
The main difference is the argument number verification and the continuation of the method
after a return in our clojures.

###Disclosure Source : robertsosinski.com
I am a student at DevBootcamp, in second week, so there is a high probability that I wrote
some stupid things; If it's the case, please let me know so I can learn more and fix it :)
jypepin.com

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