Created
April 7, 2014 19:42
-
-
Save ttscoff/10038127 to your computer and use it in GitHub Desktop.
Sum all numbers found in the input
This file contains 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/ruby | |
decimal = "." | |
separator = "," | |
if RUBY_VERSION.to_f > 1.9 | |
Encoding.default_external = Encoding::UTF_8 | |
Encoding.default_internal = Encoding::UTF_8 | |
input = STDIN.read.force_encoding('utf-8') | |
else | |
input = STDIN.read | |
end | |
def esc(char) | |
return "\\#{char}" | |
end | |
total = 0 | |
places = 0 | |
input.scan(/(\-?[\d#{esc(separator)}]+(#{esc(decimal)}\d+)?)\b/).each {|x| | |
total += x[0].gsub(/#{esc(separator)}/,'').sub(/#{esc(decimal)}/,'.').to_f | |
places = x[1].length - 1 if x[1] && x[1].length.to_i > places + 1 | |
} | |
puts input.chomp | |
out = "\n%.#{places.to_i}f" % total | |
puts out.sub(/\./,decimal) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment