我遇到了以下Ruby代码:

class MyClass
    attr_accessor :items
    ...
    def each
        @items.each{|item| yield item}
    end
    ...
end

each法有什么作用?尤其是,我不明白yield是做什么的.

推荐答案

下面是一个充实示例代码的示例:

class MyClass
  attr_accessor :items

  def initialize(ary=[])
    @items = ary
  end

  def each
    @items.each do |item| 
      yield item
    end
  end
end

my_class = MyClass.new(%w[a b c d])
my_class.each do |y|
  puts y
end
# >> a
# >> b
# >> c
# >> d

一个集合上有each个循环.在本例中,它在@items数组中的每个项上循环,在我执行new(%w[a b c d])语句时初始化/创建了@itemsarray.

MyClass.each方法中的yield itemitem传递给连接到my_class.each的块.正在生成的item被分配给本地y.

这有用吗?

现在,这里有更多关于each的工作原理.使用相同的类定义,下面是一些代码:

my_class = MyClass.new(%w[a b c d])

# This points to the `each` Enumerator/method of the @items array in your instance via
#  the accessor you defined, not the method "each" you've defined.
my_class_iterator = my_class.items.each # => #<Enumerator: ["a", "b", "c", "d"]:each>

# get the next item on the array
my_class_iterator.next # => "a"

# get the next item on the array
my_class_iterator.next # => "b"

# get the next item on the array
my_class_iterator.next # => "c"

# get the next item on the array
my_class_iterator.next # => "d"

# get the next item on the array
my_class_iterator.next # => 
# ~> -:21:in `next': iteration reached an end (StopIteration)
# ~>    from -:21:in `<main>'

请注意,在最后next次迭代时,迭代器从数组的末尾脱落.这是NOT使用块的潜在trap ,因为如果你不知道数组中有多少元素,你可能会要求太多的项,并得到一个异常.

each与块一起使用将在@items接收器上迭代,并在到达最后一项时停止,从而避免错误,并保持整洁.

Ruby相关问答推荐

当我在 Ruby 中围绕最后一个字符拆分时,如何拆分字符串?

有没有办法向用户返回 nil 消息但不中断 ruby​​ 中的应用程序?

Ruby中带和不带下划线_的方法参数有什么区别

Ruby 和用正则表达式分割字符串

Sinatra + Bundler?

将块传递给方法传递给Ruby中的另一个方法

这些 Ruby 命名空间约定之间有什么区别?

如何按长度对 Ruby 字符串数组进行排序?

如何在 linux (ubuntu) 上更新 ruby​​?

加载 RubyGems 插件时出错,openssl.bundle (LoadError)

Ruby 中的p是什么?

无法将 RVM 安装的 Ruby 与 sudo 一起使用

判断字符串是否为空的Ruby方法?

计算文件中的行数而不将整个文件读入内存?

工厂女孩 - 目的是什么?

不能在windows上安装thin

Ruby中的urldecode?

Ruby - 无法修改冻结的字符串 (TypeError)

Ruby:捕获异常后继续循环

如何在 Ubuntu 12.04 上正确安装 ruby​​ 2.0.0?