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 #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



Send Me A Message

I would love to get in touch and talk about your next project. Feel free to send a message and I will get back to you shortly.

Get Connected