Reputation: 11876
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
Upvotes: 0
Views: 1216
Reputation: 1944
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
Upvotes: 1
Reputation: 11137
To 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
Upvotes: 0
Reputation: 3803
You can do this by following
2.1.0 :031 > str = "12345"
=> "12345"
2.1.0 :032 > Integer(str) rescue 0
=> 12345
Upvotes: 4