Last active
September 3, 2015 18:36
-
-
Save aniruddha84/de564b927bdb5a5d8e1c to your computer and use it in GitHub Desktop.
Parse string to Int
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
def number_map | |
{ | |
"0" => 0, | |
"1" => 1, | |
"2" => 2, | |
"3" => 3, | |
"4" => 4, | |
"5" => 5, | |
"6" => 6, | |
"7" => 7, | |
"8" => 8, | |
"9" => 9 | |
} | |
end | |
def parse_int(str) | |
return 0 if str.nil? | |
str.strip! | |
return 0 if str.empty? | |
indices = (0 ... str.length).find_all { |i| str[i] == '.' } | |
return 0 if indices.size > 1 | |
str = str[0...indices[0]] unless indices.empty? | |
result = 0 | |
multiplier = 10 ** (str.size - 1) | |
sign = 1 | |
if str[0] == "-" | |
sign = -1 | |
str = str[1..-1] | |
end | |
str.chars.each do |c| | |
return 0 unless val = number_map[c] | |
result += val * multiplier | |
multiplier /= 10 | |
end | |
result * sign | |
end |
Code updated. Now will return 0 for invalid cases (as per Ruby behavior for similar function).
For floats, will return the integer part before the period.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what happens if you pass?