I want to return a multi-line block of code from one function to be executed by another function
for example
def foo
return #block
end
def bar(&block)
block.call
end
bar(foo)
Does any one know how to do this? Ruby 1.9.3
You need to create a Proc. There are several methods that create them — primarily proc
, lambda
and ->
. You just pass a block to one of these functions and it will wrap the block in a Proc object. (There are subtle differences in how the three methods handle arguments, but you usually don't need to care.) So you could write:
def foo
proc { puts "Look ma, I got called!" }
# you don't need the return keyword in Ruby -- the last expression reached returns automatically
end
def bar(&block)
block.call
end
bar(&foo) # You need the & operator to convert the Proc back into a block
You can return a Proc
object:
def foo
return Proc.new { ... }
end
def bar(block)
block.call
end
bar(foo)
Here's the live example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With