-
-
Save havenwood/4074172 to your computer and use it in GitHub Desktop.
A simple atoi function using ruby 2.0 refinements.
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
module AtoiString | |
refine String do | |
def atoi | |
fixed_self = fix self | |
result = 0 | |
fixed_self.each_char do |c| | |
result = result * 10 + c.to_i | |
end | |
fixed_self[0] == '-' ? -result : result | |
end | |
private | |
def fix string | |
minus = false | |
string.split('.').first.each_char do |c| | |
minus = true if c == '-' | |
break if c >= '0' && c <= '9' | |
end | |
string.each_char do |c| | |
string.delete! c if c < '0' || c > '9' | |
end | |
minus ? "-#{string}" : string | |
end | |
end | |
end | |
using AtoiString | |
'123'.atoi | |
#=> 123 | |
'-af+240.sf'.atoi | |
#=> -240 | |
';sf2.34-34'.atoi | |
#=> 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment