使用块比常规方法有什么好处?

Cri*_*tes 4 ruby

我是一名Java程序员,我正在学习Ruby ...

但是我不知道那些代码块可以让我获益...就像传递块作为参数的目的是什么?为什么没有2种专门的方法可以重复使用?

为什么块中的某些代码无法重用?

我会喜欢一些代码示例......

谢谢您的帮助 !

mik*_*kej 9

考虑一些在Java中使用匿名类的东西.例如,它们通常用于可插入行为(如事件侦听器)或参数化具有常规布局的方法.

想象一下,我们想要编写一个方法来获取一个列表并返回一个新列表,该列表包含给定列表中指定条件为真的项.在Java中我们会编写一个接口:

interface Condition {
    boolean f(Object o);
}
Run Code Online (Sandbox Code Playgroud)

然后我们可以写:

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

如果我们想从列表中选择偶数,我们可以写:

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

要在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
Run Code Online (Sandbox Code Playgroud)

然后我们可以简单地选择偶数

even = select(list) { |i| i % 2 == 0 }
Run Code Online (Sandbox Code Playgroud)

当然,这个功能已经内置在Ruby中,所以在实践中你只会这样做

even = list.select { |i| i % 2 == 0 }
Run Code Online (Sandbox Code Playgroud)

另一个例子,考虑打开文件的代码.你可以这样做:

f = open(somefile)
# work with the file
f.close
Run Code Online (Sandbox Code Playgroud)

但是,您需要考虑将您close置于一个ensure块中,以防在使用该文件时发生异常.相反,你可以做到

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