ruby - 与常规方法相比,使用 block 可以获得什么好处?

标签 ruby

我是一名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/

相关文章:

ruby-on-rails - postgres Gem::Ext::BuildError:在 OSX 上安装 'pg' 时无法构建 gem native 扩展

ruby-on-rails - Rails 服务器运行,但 Rails 控制台抛出错误 "not checked out yet"

ruby - 如果哈希数组具有属性/值对,如何编写 rspec 测试

ruby - 在 Ruby 中逐像素读取图像

mysql - 获取带有 EST 时区时间的游戏

ruby-on-rails - 显示 i18n 的 Rails t 函数

ruby-on-rails - 为什么 Module.sum( :field) is integer?

ruby - 错误 : SASS installation for windows

ruby-on-rails - 在 hstore 属性上使用 update_columns

ruby - 如何使用修改后的 header 制作 HTTP GET?