Skip to content

Instantly share code, notes, and snippets.

@seanhenry seanhenry/LineCounter.rb
Last active Nov 6, 2015

What would you like to do?
A script which counts lines of code in Swift and Objective-C projects. It ignores blank lines and counts production code and test code separately. It provides the average number of lines per file and the standard deviation.
# Usage: ruby LineCounter.rb <directory to search>
class LineCounter
def initialize(lineCounts)
@lineCounts = lineCountsFromString(lineCounts)
def lineCountsFromString(string)
lineCountsStrings = string.split("\n")
return { |e| e.to_i }
def standardDeviation
variance = @lineCounts.reduce(0) { |v, e| v + (mean - e)**2 }
variance = variance / (entries - 1).to_f
standardDeviation = Math.sqrt(variance)
def mean
fileCount = @lineCounts.length
meanLineCount = sum / fileCount
def sum
return @lineCounts.reduce(:+)
def entries
directory = ARGV.last
excludeDependencies = "--exclude-dir=Carthage --exclude-dir=Pods"
includeFiles = "--include=*.swift --include=*.m"
excludeTests = "--exclude-dir=*Tests"
emptyLinePattern = "'^[[:space:]]*$'"
includeTestFiles = "--include=*Tests.swift --include=*Tests.m"
productionLineCounter =`grep #{includeFiles} #{excludeTests} #{excludeDependencies} --no-filename -cvr -e #{emptyLinePattern} #{directory}`)
testLineCounter =`grep #{includeTestFiles} #{excludeDependencies} --no-filename -cvr -e #{emptyLinePattern} #{directory}`)
puts "There are #{productionLineCounter.sum} lines of production code."
puts "There are #{testLineCounter.sum} lines of test code."
puts "There are #{productionLineCounter.entries} production files."
puts "The mean line count for production code is #{productionLineCounter.mean}."
puts "The standard deviation for production code is #{productionLineCounter.standardDeviation}."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.