Advertisement
Guest User

Untitled

a guest
Jan 16th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.44 KB | None | 0 0
  1. # Scan a given string for only numbers.
  2. # Transform to int and add to a running total.
  3. def total_from_string(str)
  4. str.scan(/(\d+)/).flatten.reduce(0) { |total, value| total += value.to_i }
  5. end
  6.  
  7. puts total_from_string("In 2015, I want to know how much does iPhone 6+ cost?") == 2021 # True
  8. puts total_from_string("Also splits floats like 3.4 correctly") == 7 # True
  9. puts total_from_string("Ignores integer signs such as -123 and +123") == 246 # True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement