Created
April 3, 2012 17:07
-
-
Save pfleidi/2293727 to your computer and use it in GitHub Desktop.
Stupid implementation of the unix tool wc in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| require 'optparse' | |
| options = {} | |
| # parse commandline options | |
| OptionParser.new do |opts| | |
| opts.banner = "Usage: #{__FILE__} [-lmw] [file]" | |
| opts.on('-l', '--lines', 'The number of lines in input file') do | |
| options[:lines] = true | |
| end | |
| opts.on('-w', '--words', 'The number of words in input file') do | |
| options[:words] = true | |
| end | |
| opts.on('-m', '--chars', 'The number of bytes in input file') do | |
| options[:chars] = true | |
| end | |
| opts.on( '-h', '--help', 'Display this screen' ) do | |
| puts opts | |
| exit | |
| end | |
| end.parse! | |
| # output all values if no option is given | |
| if options.empty? | |
| options = { | |
| :lines => true, | |
| :words => true, | |
| :chars => true | |
| } | |
| end | |
| file_name = ARGV.last | |
| content = "" | |
| # read from stdin (pipe) if no file is given | |
| if file_name | |
| content = IO.read(file_name) | |
| else | |
| content = ARGF.read | |
| end | |
| # calulate metrics | |
| options.each do |key, value| | |
| case key | |
| when :lines | |
| print "\t#{content.split(/\n/).length}" | |
| when :words | |
| print "\t#{content.split(/\s/).length}" | |
| when :chars | |
| print "\t#{content.length}" | |
| end | |
| end | |
| print "\t#{file_name}" if file_name | |
| print "\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is another implementation via Ruby 2.0 and its feature
Enumerator#lazy