我是一名Java程序员,正在学习Ruby...
但我不明白这些代码块可以给我带来什么……比如将代码块作为参数传递的目的是什么?为什么不使用 2 个可以重复使用的专门方法呢?
为什么 block 中有一些代码不能重用?
我想要一些代码示例...
感谢您的帮助!
最佳答案
考虑一些您将在 Java 中使用匿名类的事情。例如它们通常用于可插入的行为,例如事件监听器或参数化具有通用布局的方法。
假设我们要编写一个方法,它接受一个列表并返回一个新列表,其中包含给定列表中指定条件为真的项目。在 Java 中,我们会编写一个接口(interface):
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
block 中,以防在处理文件时发生异常。相反,你可以做
open(somefile) do |f|
# work with the file here
# ruby will close it for us when the block terminates
end
关于ruby - 与常规方法相比,使用 block 可以获得什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4783166/