簡體   English   中英

Ruby:如何創建一個塊並將其作為參數傳遞?

[英]Ruby: How to create a block and pass it as an argument?

我正在使用一個以塊為參數的方法。 我是Ruby和Blocks的新手,所以我不太明白如何創建一個Block並將其傳遞給方法。 能否請您舉例說明如何創建一個塊並將其作為參數傳遞?

更新:這是我嘗試調用的方法的示例:

def exec!(commands, options=nil, &block)
  # method code here
  # eventually it will execute the block if one was passed
end

以下是我目前調用此方法的方法:

@result = ssh.exec!("cd /some/dir; ls")

如何將塊作為第三個參數傳遞給exec! 方法?

這部分取決於您希望如何使用它。 如果它符合您的使用需求,這是一個簡單的方法:

@result = ssh.exec!("cd /some/dir; ls") do |something|
    # Whatever you need to do
    # The "something" variable only makes sense if exec! yields something
end

要么

@result = ssh.exec!("cd /some/dir; ls") { |something| puts something }

當塊很短時,通常使用{}表示法。

你也可以創建一個Proc或lambda; 最終“正確”的答案取決於你想要做什么。

請注意,如果您正在談論Net :: SSH,那么就有一個例子

還有一件事。 您還可以創建Proc-object(或任何具有'to_proc'方法的對象)並使用該Proc-object作為最后一個參數調用您的方法,並在其前面加上'&'符號。 例如:

proc = Proc.new { |x| puts x }
%w{1 2 3}.each(&proc)

做同樣事情的其他方式:

%w{1 2 3}.each { |x| puts x }

如何使用關鍵字yield來理解傳遞塊參數?

例如,我們有:

def our_method
  puts "we're going to call yield operator"
  yield "this is message from our_method"
  puts "we called the yield operator"
end

our_method { |message| puts message }

我們將得到這個結果:

we're going to call yield operator
this is message from our_method
we called the yield operator

這個怎么運作?

當我們調用our_method時,我們也將參數傳遞給它,在我們的例子中它是一個塊 -

{ |message| puts message } { |message| puts message }

our_method中它執行第一個字符串並將打印“我們將調用yield運算符”

然后是收益率運算符的轉向。 它幾乎等同於block.call但除此之外,它將消息作為參數傳遞給塊。 這就是該塊將從our_method打印字符串的原因。

最后,our_method打印最終字符串“我們稱之為yield運算符”

暫無
暫無

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

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