I am currently looking for a software/web development job preferably as a Rails-based developer.
Please email me at weston@westonganger.com. Thanks in advance for any leads!

Skipping Lines When Reading Files In Ruby

Posted by Weston Ganger

I needed to read a ruby file but I wanted to skip the first and last lines in it.

Here are a few different methods.

# BEST METHOD, using a range, skips first and last line
File.readlines(myfile.rb)[1..-2].each do |line| 
  puts line

# using drop, skips first line
File.readlines(myfile.rb).drop(1).each do |line| 
  puts line

# using enumerator, skips first line
File.readlines(myfile.rb).each do |file, w|
  lines = file.lines # an enumerator
  lines.next #skips first line
  lines.each do |line|
    puts line

I was using it for the prawn gem, because I had .pdf.prawn files that I was rendering from controller actions that required the first and last line, but I was also concatenating pdf’s in a different method that had to have the first and last lines in the method not the file.

Related External Links:

Article Topic:Software Development - Rails

Date:May 23, 2015

Recommended Posts