Skip to content

Instantly share code, notes, and snippets.

@rubyonrailstutor
Created June 23, 2012 23:16
Show Gist options
  • Save rubyonrailstutor/2980508 to your computer and use it in GitHub Desktop.
Save rubyonrailstutor/2980508 to your computer and use it in GitHub Desktop.
Blocks, Procs and Lambda
#HOW A LAMBDA WORKS
var1 = lambda {|x,y| puts x + y}
var1.call(1,0)
#running the above will result in 1
#HOW YIELD WORKS
def method1
yield
end
method1{ puts "this is a yield block"}
#the above will insert the contents of
#curly brace into method1 and print
#this is a yield block
#HOW A PROC WORKS
# PROC is a passable block
x = Proc.new{puts "string 1"}
def method2
yield
end
method2 &x
#the above will output "string 1"
#the proc x is passed into method call
#HOW TO PASS A BLOCK BETWEEN METHODS
def methodX(&newblock)
p "string 1"
methodZ(&newblock)
p "string 3"
end
def methodZ
yield
end
methodX{ p "string 2"}
#methodX passes the block which gets
#called via methodZ
#output is "string1" "string2" "string3"
#HOW TO USE LAMBDA, ie, Parameter enforcement
var1 = lambda{|x,y| p x + y}
var1.call(1,2)
#var1 has to be passed x,y parameters to work
#above prints 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment