Skip to content

Instantly share code, notes, and snippets.

@spraints
Created April 11, 2013 12:09
Show Gist options
  • Save spraints/5362874 to your computer and use it in GitHub Desktop.
Save spraints/5362874 to your computer and use it in GitHub Desktop.
fun with procs, blocks, and lambdas
def a
[1,2,3].each do |x|
return :a if x == 2
end
:not_a
end
def a2
block = lambda { |x| return :a if x == 2 }
[1,2,3].each(&block)
end
def a3
block = Proc.new { |x| return :a if x == 2 }
[1,2,3].each(&block)
end
def ab1
last = nil
[1,2,3].each do |x|
last = x
break if x == 2
end
last
end
def ab2
last = nil
block = lambda do |x|
last = x
break if x == 2
end
[1,2,3].each(&block)
last
end
def ab3
return :ab3
last = nil
block = Proc.new do |x|
last = x
break if x == 2
end
[1,2,3].each(&block)
last
end
def b
[1,2,3].map do |x|
return :b if x == 2
end
:not_b
end
def c
File.open(__FILE__) do |f|
return :c
end
:not_c
end
def d
d1 { return :d }
end
def d1(&block)
x = Object.new
x.instance_variable_set(:@block, block)
def x.inspect
@block.call.inspect
end
#x.inspect
end
p a
p a2
p a3
p [ab1, ab2, ab3]
p b
p c
p d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment