我一直在学习 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 array
是array.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/