Skipping Lines When Reading Files In Ruby

Posted by Weston Ganger on May 23, 2015

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:

Posted in Rails and Tagged with ruby readlines rails 

Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts