0

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

3
  • You can find the source here: ruby-doc.org/core-2.2.2/String.html#to_i-method Commented May 26, 2015 at 12:19
  • Integer(a.delete('^0-9')) rescue 0 ... Commented May 26, 2015 at 12:43
  • What’s wrong with to_i? Commented May 26, 2015 at 15:14

3 Answers 3

4

You can do this by following

2.1.0 :031 > str = "12345"
 => "12345" 
2.1.0 :032 > Integer(str) rescue 0
 => 12345 
Sign up to request clarification or add additional context in comments.

2 Comments

It throws error when I pass character in my 'str' - ArgumentError: invalid value for Integer: "1234abcd">
It will give throws an ArgumentError. So it is always better to use to_i which will not give an error even if it is not a valid integer
1

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

1 Comment

best answer IMO as it is the closest to doing what the question seems to be looking for: converting to integer without using #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 48
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.