En tant que formateur Ruby, je rencontre régulièrement des développeurs manipulant les block, Proc et lambda sans toujours comprendre comment cela fonctionne. J'ai donc eu l'idée de faire cette présentation au Meetup Paris.rb. (10 décembre 2012)
7. yield - Return value
def puts_this_block
block_result = yield
puts block_result
end
puts_this_block {"Matz"} Matz
7
8. yield - Optional block
def call_this_block
yield("Matz")
end
call_this_block no block given
8
9. yield - Optional block
def call_this_block
yield("Matz") if block_given?
end
call_this_block
9
10. yield - Scope 1
def call_this_block
yield
end
x = 5
puts "value of x before: #{x}" value of x before: 5
call_this_block { x += 1 }
puts "value of x after: #{x}" value of x after: 6
10
11. yield - Scope 2
def call_this_block
x = 100
yield
puts "value of x at end of call_this_block_x: #{x}"
end
x = 5 value of x at end of
call_this_block { x += 1 } call_this_block_x: 100
puts "value of x after: #{x}" value of x after: 6
11
12. What if we wanted to store this
block, for execution later?
{|name| puts name}
12
15. Proc vs lambda : return
Lambda
def bar
f = lambda { return "return from inside lambda" }
f.call
return "return from bar"
end
puts bar return from bar
Proc
def foo
f = Proc.new { return "return from inside proc" }
f.call
return "return from foo"
end
puts foo return from inside proc
15