[英]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.