Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i return a block of code in ruby

Tags:

return

ruby

block

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

like image 331
user2394397 Avatar asked Jan 11 '23 00:01

user2394397


2 Answers

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
like image 135
Chuck Avatar answered Jan 22 '23 01:01

Chuck


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.

like image 40
Shoe Avatar answered Jan 22 '23 01:01

Shoe