我是一名Java程序员,正在学习Ruby...
但我不明白那些代码块能给我带来什么好处...比如将代码块作为参数传递的目的是什么?为什么不使用两个专门的方法来实现可重用性?
为什么有些代码在块中不能被重用?
我希望能够看到一些代码示例...
谢谢你的帮助!
我是一名Java程序员,正在学习Ruby...
但我不明白那些代码块能给我带来什么好处...比如将代码块作为参数传递的目的是什么?为什么不使用两个专门的方法来实现可重用性?
为什么有些代码在块中不能被重用?
我希望能够看到一些代码示例...
谢谢你的帮助!
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;
}
});
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 }
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