Differences

This shows you the differences between two versions of the page.

Link to this comparison view

rubywc [2014/10/26 01:52] (current)
Line 1: Line 1:
 +==== Word count (wc) in Ruby ====
 +<code lang="​ruby">​
 +# wc.rb
  
 +require '​optparse'​
 +
 +ProgramOptions = Struct.new(:​onlyChars,​ :onlyWords, :onlyLines, :count)
 +
 +options = ProgramOptions.new(true,​ false, false,"​0"​)
 +
 +opts = OptionParser.new
 +
 +#p options
 +
 +opts.on("​-c","​--char",​nil,"​Count characters"​) { options.onlyChars = true; ARGV.delete("​-c"​);​ ARGV.delete("​--char"​) }
 +opts.on("​-w","​--word",​nil,"​Count words"​) { options.onlyWords = true; ARGV.delete("​-w"​);​ ARGV.delete("​--word"​) }
 +opts.on("​-l","​--line",​nil,"​Count lines"​) { options.onlyLines = true; ARGV.delete("​-l"​);​ ARGV.delete("​--line"​) }
 +opts.on("​-r","​--require N", Integer, "​Required argument"​) { |val| options.count = val; ARGV.delete("​-r"​);​ ARGV.delete("​--require"​);​ ARGV.delete(val.to_s) }
 +opts.on("​-h","​--help",​nil,"​Print this help") { puts opts; exit }
 +begin
 + opts.parse(ARGV)
 +rescue
 + puts "​*ERROR* : Invalid argument passed"​
 + puts opts
 +end
 +
 +#p options
 +#p ARGV
 +
 +SPACE = ' '
 +CR = 10
 +LF = 13
 +TAB = 9
 +
 +def handleFile(fin,​name,​options)
 + charCount = lineCount = wordCount = 0
 + fin.each_byte { |c|
 + charCount += 1
 + if c == SPACE || c == TAB || c == CR || c == LF
 + wordCount += 1
 + end
 + if c == CR || c == LF
 + lineCount += 1
 + end
 + }
 + printf "%6d Characters %s\n",​charCount,​name if options.onlyChars
 + printf "%6d Word       ​%s\n",​wordCount,​name if options.onlyWords
 + printf "%6d Lines      %s\n",​lineCount,​name if options.onlyLines
 + puts
 +end
 +
 +if ARGV.empty?
 + handleFile(STDIN,"​STDIN",​options)
 +else
 + ARGV.each { |inp|
 + fh = File.open(inp,​ "​r"​)
 + handleFile(fh,​inp,​options)
 + fh.close
 + }
 + exit
 +end
 +
 +</​code>​
 +----
 +  * [[rubyinfo|Back to Ruby]]
rubywc.txt ยท Last modified: 2014/10/26 01:52 (external edit)
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0