[Rails] Re: How to edit each line of a file in ruby, without using a temp file
Walter Davis wrote in post #1078369:
> On Oct 2, 2012, at 12:00 AM, Nila wrote:
>
>> test02,a
>> Writing it to a temporary file and then replace the original file works,
> However, I need to edit the file quite often and therefore prefer to do
> it within
> the file itself .Any pointers are appreciated.
> You can stash the data in an array, manipulate it there, and then write
> it back to the file store after. Ignore the HEREDOC parts of this, and
> substitute your file read/write bits, and this should work:
>
> foo = <<EOF
> one
> two
> three
> EOF
> bar = []
> foo.each_line do |line|
> bar.push (line.strip + ',a')
> end
> foo = bar.join("\n")
> puts foo
Keep in mind that doing it this way will load the entire file into RAM,
may not be an issue given today's servers have lots of RAM. However,
doing what Colin suggested, using a database, would almost certainly be
the more efficient solution.
--
Posted via http://www.ruby-forum.com/.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home