I'm Jason, a web application developer in East Tennessee.

How to 'head' a text file in Ruby

I wanted to just view the first 20 lines of a 10,000 line CSV file returned by an API in a Ruby on Rails project I’m working on. Here is the chain of Ruby commands I came up with to effectively ‘head’ the CSV document returned.

>> csv = "first line\nsecond line\nthird line\nfourth line\nfifth line\nsixth line\n"
>> csv.split("\n")[0..3].join("\n")
=> "first line\nsecond line\nthird line\nfourth line"
comments powered by Disqus