How to transfer a block to another in Ruby?

Assuming I have the following proc:

a = Proc.new do
    puts "start"
    yield
    puts "end"
end

It is also assumed that I pass to aanother method, which subsequently calls instance_evalin another class with this block, how can I pass the block to the end of this method, which is obtained in a.

For instance:

def do_something(a,&b)
    AnotherClass.instance_eval(&a) # how can I pass b to a here?
end

a = Proc.new do
    puts "start"
    yield
    puts "end"
end

do_something(a) do
    puts "this block is b!"
end

The output should, of course, be:

start
this block is b!
end

How to transfer the secondary unit to in instance_eval?

I need something like this at the heart of the Ruby template system I'm working on.

+5
source share
2 answers

You cannot use income in a. Rather, you need to pass an object Proc. This will be the new code:

def do_something(a,&b)
    AnotherClass.instance_exec(b, &a)
end

a = Proc.new do |b|
    puts "start"
    b.call
    puts "end"
end

do_something(a) do
    puts "this block is b!"
end

yield . instance_exec ( Ruby 1.9), . - Proc b a, Proc#call().

+5
a=Proc.new do |b|
    puts "start"
    b.call
    puts "end"
end
def do_something(a,&b)
  AnotherClass.instance_eval { a.call(b) }
end
0

All Articles