加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 对于常规方法,块可以获得什么增益?

发布时间:2020-12-17 03:58:38 所属栏目:百科 来源:网络整理
导读:我是一名 Java程序员,我正在学习 Ruby … 但是我不知道那些代码块可以让我获益…就像传递块作为参数的目的是什么?为什么没有2种专门的方法可以重复使用? 为什么块中的某些代码无法重用? 我会喜欢一些代码示例…… 谢谢您的帮助 ! 解决方法 考虑一些在Jav
我是一名 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

但是你需要考虑将你的关闭放在一个确保块中,以防在使用该文件时发生异常.相反,你可以做到

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读