Atoi Implementation in Ruby
Published in
1 min readJul 17, 2014
Prompt: Implement your own string to number conversion function. Do not use the following: send, eval, to_i, to_f, Integer(str), Float(str), or any similar method to convert your strings to numbers in your RPN evaluator.
You will definitely need “atoi” — converts an ASCII string to an integer. E.g., atoi(“251”) returns the integer 251.
Note: String#bytes is only available in ruby 2.0 and above.
The equivalent to str.bytes is to chain str.each_byte.to_a
Refactored
ASCII_NUM_START = 48
def ascii_to_i(int_as_str) #example: "22"
array_ascii = int_as_str.bytes # [50,50]
converted_arr = array_ascii.map {|ascii| ascii - ASCII_NUM_START } # [2,2]
converted_arr.inject { |sum, n| sum * 10 + n } # 22
end