Skip to content

Instantly share code, notes, and snippets.

@havenwood
Forked from stcatz/atoi.rb
Created November 14, 2012 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/4074172 to your computer and use it in GitHub Desktop.
Save havenwood/4074172 to your computer and use it in GitHub Desktop.
A simple atoi function using ruby 2.0 refinements.
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