Created
January 16, 2017 19:07
-
-
Save ChanChar/28ffda57c7f44b49b663647e0cf46453 to your computer and use it in GitHub Desktop.
Parse and sums the integers within a sentence.
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
# Scan a given string for only numbers. | |
# Transform to int and add to a running total. | |
def total_from_string(str) | |
str.scan(/(\d+)/).flatten.reduce(0) { |total, value| total += value.to_i } | |
end | |
puts total_from_string("In 2015, I want to know how much does iPhone 6+ cost?") == 2021 # True | |
puts total_from_string("Also splits floats like 3.4 correctly") == 7 # True | |
puts total_from_string("Ignores integer signs such as -123 and +123") == 246 # True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment