簡體   English   中英

使用塊比常規方法有什么好處?

[英]What's the gain I can have with blocks over regular methods?

我是一名Java程序員,我正在學習Ruby ...

但是我不知道那些代碼塊可以讓我獲益...就像傳遞塊作為參數的目的是什么? 為什么沒有2種專門的方法可以重復使用?

為什么塊中的某些代碼無法重用?

我會喜歡一些代碼示例......

謝謝您的幫助 !

考慮一些在Java中使用匿名類的東西。 例如,它們通常用於可插入行為(如事件偵聽器)或參數化具有常規布局的方法。

想象一下,我們想要編寫一個方法來獲取一個列表並返回一個新列表,該列表包含給定列表中指定條件為真的項。 在Java中我們會編寫一個接口:

interface Condition {
    boolean f(Object o);
}

然后我們可以寫:

public List select(List list, Condition c) {
    List result = new ArrayList();
    for (Object item : list) {
        if (c.f(item)) {
            result.add(item);
        }
    }
    return result;
}

如果我們想從列表中選擇偶數,我們可以寫:

List even = select(mylist, new Condition() {
    public boolean f(Object o) {
        return ((Integer) o) % 2 == 0;
    }
});

要在Ruby中編寫等價物,可以是:

def select(list)
  new_list = []
  # note: I'm avoid using 'each' so as to not illustrate blocks
  # using a method that needs a block
  for item in list
    # yield calls the block with the given parameters
    new_list << item if yield(item)
  end
  return new_list
end

然后我們可以簡單地選擇偶數

even = select(list) { |i| i % 2 == 0 }

當然,這個功能已經內置在Ruby中,所以在實踐中你只會這樣做

even = list.select { |i| i % 2 == 0 }

另一個例子,考慮打開文件的代碼。 你可以這樣做:

f = open(somefile)
# work with the file
f.close

但是你需要考慮將你的close放在一個ensure塊中,以防在使用該文件時發生異常。 相反,你可以做到

open(somefile) do |f|
  # work with the file here
  # ruby will close it for us when the block terminates
end

塊背后的想法是它是一個高度本地化的代碼,在調用站點上有定義是有用的。 您可以使用現有函數作為塊參數。 只需將其作為附加參數傳遞,並在其前面加上&

暫無
暫無

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

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