我写了一些代码:
output = File.open(text_file).collect.reverse.join("<BR>")
它似乎在1.8.7上工作正常,但抛出错误
NoMethodError - undefined method 'reverse' for #<Enumerator: #<File:C:\EduTester\cron\rufus.log>:collect>:
1.9.1(ruby 1.9.3p194(2012-04-20)[i386-mingw32])
有人知道为什么会发生这种情况以及如何解决这个问题?(为什么我最感兴趣.)
首先如何解决它 - 你应该这样做:
output = File.open(text_file).to_a.reverse.join("<BR>")
Run Code Online (Sandbox Code Playgroud)
这适用于任何一个版本的Ruby.基本上你需要.to_a在反转它们并添加换行符之前将文件转换为一个行数组(with ).
就其原因而言(这有点技术性):File在Enumerable模块中混合,它给出了类似的方法collect.现在在Ruby 1.87中,如果你在Enumberable.collect没有块的情况下调用它将返回一个Array.但是在1.9中,它返回一个Enumerator- 它不响应该reverse方法.
以下是该方法的2个版本:
http://ruby-doc.org/core-1.8.7/Enumerable.html#method-i-collect
http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-collect
所以基本上1.9之前.collect是一个(hacky)相当于.to_a.但总是.to_a用来把东西变成数组.