file
-
Ruby’s
File.readlinesmethod can be used in most common situations as a replacement for PHP’sfilefunction.PHP
$lines = file('/path/to/foobar'); var_export($lines); // => array(0 => 'hello\n', 1 => 'there')
Ruby
lines = File.readlines('/path/to/foobar') p lines # => ['hello\n', 'there']
Notice above that both PHP’s
filefunction and Ruby’sFile.readlinesmethod both return the line separators at the end of each array element. Thefilefunction has a second optional argument,flags, that accepts constants likeFILE_IGNORE_NEW_LINES. In Ruby, you’ll need to do this filtering yourself.A second important difference is that
File.readlineshas a second optional argument,separator, that defaults to\n. This is quite different from PHP, where PHP determines the separator based on the operating system or theauto_detect_line_endingsruntime configuration option.Iterating Over Lines
Often times you want to iterate over each line in a file and perform an operation using the line. You can use Ruby’s
File.readlinesto read the lines into an array and then iterate over that array. However, this can be costly when working with large files.A better solution for these circumstances is to open a
Fileinstance and then pass a block to theeach_linemethod.Ruby
File.open('/path/to/foobar') do |file| file.each_line do |line| puts line end end
The snippet above will only read one line of the file into memory at a time, whereas
File.readlineswill load the entire file into an array.see also
Looking for Rails or PHP web application development, integration, and training?
Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.

