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/4074170 to your computer and use it in GitHub Desktop.
Save havenwood/4074170 to your computer and use it in GitHub Desktop.
A simple atoi function in ruby.
# A simple translate from a string to integer.
# A minus before all numbers will be consider to be a negative number.
def atoi(str)
return str if !str.is_a? String
fixed_str = fix(str)
result = 0
fixed_str.each_char do |c|
result = result*10 + c.to_i
end
fixed_str[0]=='-' ? -result : result
end
def fix(str)
minus = false
str = str.split('.').first
#Consider a minus symbol before all numbers as a negative number.
str.each_char do |c|
minus = true if c == '-'
break if( c>='0' && c<='9')
end
str.each_char do |c|
str.delete!(c) if(c<'0' || c>'9')
end
minus ? "-#{str}" : str
end
atoi('123').should == 123
atoi('-af+240.sf').should == -240
atoi(';sf2.34-34').should == 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment