ruby - "each"在ruby中使用'for each'的函数实现

标签 ruby irb

我一直在学习 ruby​​,并且有兴趣了解数组类中的“each”是如何实现的。我看到一个documentation here看起来“each”是这样写的;

# within class Array...
def each
  for each element
    yield(element)
  end
end

我确实在 ruby​​ 控制台(我使用的是 1.9.2)中准确地编写了上面的代码(没有注释#)并得到了这个语法错误

:SyntaxError: (irb):2: syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '('
(irb):5: syntax error, unexpected keyword_end, expecting $end

这是由于不完整的数组类实现而发生的(即未定义“元素”还是因为其他原因?我还想知道“每个”和其他基本功能是如何实现的。任何对正确的文档/答案会有所帮助。让我知道这是否重复(我没有看到任何类似的问题)。谢谢

最佳答案

你可以这样做(不要错过 in):

class Array
  def each
    for element in self
      yield element
    end
  end
end

但事实是:

for element in arrayarray.each的语法糖

所以上面的代码变成了这样:

class Array
  def each
    each do |element|
      yield element
    end
  end
end

还有你的 stackoverflow。

关于ruby - "each"在ruby中使用'for each'的函数实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8501065/

相关文章:

Ruby Gems 无法运行

ruby-on-rails - 如何有效地检查一组记录的 updated_at 和 created_at 是否相等

ruby-on-rails - 无法使用 Ruby 1.9 和 Rails 2.3.4 启动脚本/控制台

ruby-on-rails - 为什么 Date.today 在 Ruby 控制台 (irb) 上不起作用?

ruby - 在 IRB 中使用 ice_cube Ruby gem

mysql - Rails 在数据库中创建和更新数组

ruby - 有什么方法可以更改 Ruby 中引用的对象吗?

ruby-on-rails - 如何为 Devise 的用户名添加 slug?

ruby-on-rails - 如何从命令行退出 IRB? (在mac上使用终端)

ruby - "if/unless"等是什么类