I want to convert given string into integer without using ruby to_i method.
Basically, I want to know how to_i was implemented or what is the best way to do that. Eg :
a = '1234'
result
a = 1234
Thanks in advance
You can do this by following
2.1.0 :031 > str = "12345"
=> "12345"
2.1.0 :032 > Integer(str) rescue 0
=> 12345
Used to do it using this method in C, it might help you get an idea :
def too_i(number)
return 0 if (lead = number[/^\d+/]).nil?
lead.bytes.reduce(0) do |acc, chaar|
# 48 is the byte code for character '0'.
acc*10 + chaar - 48
end
end
too_i '123'
# => 123
too_i '123lol123'
# => 123
too_i 'abc123'
# => 0
too_i 'abcd'
# => 0
#to_i (Integer(str) is not that different imo). With this you at least learn that the digits begin at 48 (zero) on the ascii chart and that to convert to integer you get the ascii value via #bytes and subtract 48To be aware what is the main difference is Integer will throw an Exception if its not a valid integer, but to_i will try to convert as much as it can and you can rescue from Integer in case its not a valid integer as following
str = "123"
num = Integer(str) rescue 0 # will give you 123
num = str.to_i # will give you 123
str = "123a"
num = Integer(str) rescue 0 # will give you 0 - will throw ArgumentError in case no rescue
num = str.to_i # will give you 123
Integer(a.delete('^0-9')) rescue 0...to_i?