簡體   English   中英

如何在Ruby中將塊傳遞給另一個塊?

[英]How to pass a block to another in Ruby?

假設我有以下過程:

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

還假設我通過a到隨后調用另一個方法instance_eval與該塊另一個類,我怎樣才能現在通過一個塊在其上得到在產生該方法的最后a

例如:

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

輸出當然應該是:

start
this block is b!
end

如何將輔助塊傳遞給instance_eval

我需要這樣的東西作為我正在研究的Ruby模板系統的基礎。

你不能在a使用yield。 相反,您必須傳遞Proc對象。 這將是新代碼:

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()調用它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM