Skip to content

Instantly share code, notes, and snippets.

@aniruddha84
Last active September 3, 2015 18:36
Show Gist options
  • Save aniruddha84/de564b927bdb5a5d8e1c to your computer and use it in GitHub Desktop.
Save aniruddha84/de564b927bdb5a5d8e1c to your computer and use it in GitHub Desktop.
Parse string to Int
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
@senthil1216
Copy link

what happens if you pass?

"4.3"
"132213214282020324392311201238123093113401382340923892349342923482829"
"-0"
"3.222223213131131313131"
"0.000000000003"

@aniruddha84
Copy link
Author

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