I wrote some code:
output = File.open(text_file).collect.reverse.join("<BR>")
It seems to work okay on 1.8.7 but throws the error
NoMethodError - undefined method 'reverse' for #<Enumerator: #<File:C:\EduTester\cron\rufus.log>:collect>:
on 1.9.1 (ruby 1.9.3p194 (2012-04-20) [i386-mingw32])
Does somebody know why this happens and how to fix this? (Why is of most interest to me.)
First how to fix it – you should be doing this:
This will work on either version of Ruby. Basically you need to turn the file into an array of lines (with
.to_a) before reversing them and adding line breaks.In terms of the why (this gets a little technical):
Filemixes in theEnumerablemodule, which gives it methods likecollect. Now in Ruby 1.87, if you calledEnumberable.collectwithout a block it would return anArray. But in 1.9, it returns anEnumerator– which doesn’t respond to thereversemethod.Here are the 2 versions of the method in question:
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
So basically before 1.9
.collectwas a (hacky) equivalent to.to_a. But always use.to_ato turn something into an array.