Ruby Snippets

This is a collection of Ruby code snippets that I frequently use in building larger scripts. Most of my scripting tends to be for processing text files – e.g. for extracting interesting data from a log file, converting file formats, etc. – and so a lot of the snippets are of that flavor. Many of these snippets or similar can be found in books or other web sites and in these cases, appropriate references to those other sources are provided.

Reading Text Files

#1: Process each line in a text file one line at a time.

File.new('foo.txt', 'r').each() do |line|
# Process the line
print line
end

#2: Read all the lines of a text file into a list with some simple processing per line.

lines = File.new('foo.txt', 'r').collect() do |line|
line.strip()
end

#3: Read all the lines of a text file into an array if they match a certain pattern.

lines = File.new('foo.txt', 'r').select do |line|
line =~ /pattern/
end

CSV Files

#4: Generate a csv file – write rows to csvout.csv
Reference: Ruby standard language documentation for CSV module

require 'csv'
outfile = File.open('csvout.csv', 'wb')
CSV::Writer.generate(outfile) do |csv|
  csv << ['c1', nil, 5]
  csv << ['c2', 1, 2, 'abc']
end
outfile.close

#5: Read lines from a csv file
Reference: Ruby standard language documentation for CSV module

require 'csv'
CSV::Reader.parse(File.open('csvout.csv', 'rb')) do |row|
# Process the row
p row[0].data    # e.g. print the contents of the first cell
end

Array Processing

#6: Remove duplicates from an array
Reference: Ruby standard language documentation for Array module

dups = [8,1,2,1,4,4,5,7,8,5]
trimmed = dups.uniq

Misc

#7: Deep Copy
Reference: RubyForge Code Snippets – Deep Copy

class Object
def deep_clone
Marshal.load(Marshal.dump(self))
end
end

2 thoughts on “Ruby Snippets

Leave a Reply

Your email address will not be published. Required fields are marked *