Skip to content

Instantly share code, notes, and snippets.

@bmnick
Created May 16, 2012 19:41
Show Gist options
  • Save bmnick/2713357 to your computer and use it in GitHub Desktop.
Save bmnick/2713357 to your computer and use it in GitHub Desktop.
Reimplementing wc for fun in ruby
require 'optparse'
require 'pp'
options = {}
counts = []
def count_stream stream, options
counts = []
if options[:line]
counts << stream.read.split(/\n/).length
stream.rewind
end
if options[:word]
counts << stream.read.split.length
stream.rewind
end
if options[:character]
counts << stream.read.length
stream.rewind
end
counts
end
optparse = OptionParser.new do |opts|
opts.banner = "usage: wc [-clmw] [file ...]"
options[:line] = false
opts.on( '-l', 'Count Lines' ) do
options[:line] = true
end
options[:word] = false
opts.on( '-w', 'Count words' ) do
options[:word] = true
end
options[:character] = false
opts.on( '-c', 'Count Characters' ) do
options[:character] = true
end
end
# Parse flags and leave just files
optparse.parse!
# Turn on all counts if none are on
if options.all? { |key, active| active == false }
options.keys.each do |opt|
options[opt] = true
end
end
# Iterate over arguments and count
unless ARGV.empty?
counts = ARGV.map do |file|
count_stream(File.open(file), options) << file
end
else
counts << count_stream(STDIN, options)
end
counts.each do |count|
count.each do |num|
print "\t#{num}"
end
puts
end
if counts.length > 1
totals = counts.reduce do |total, cur|
[total[0]+cur[0], total[1] + cur[1], total[2] + cur[2]]
end
totals.each do |num|
print "\t#{num}"
end
puts "\ttotal"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment