Adel Almaleh Adel Almaleh - 4 months ago 12
Ruby Question

What can I use instead of char.to_i?

For an assignment I need to write a method named

get_integer_from_string
that will convert an input string to an integer.
I've completed it, but for one requirement:


  • Please DO NOT use implicit or automatic type casting to solve this
    problem, i.e. atoi() in C, int()in Python, functions like parseInt()
    in Java or intval() in PHP



What can I replace
char.to_i
with in my code below to satisfy this requirement?

def get_integer_from_string(str, based=7)
return 0 if (/^(?<num>\d+)$/ =~ str).nil?
result = 0
str.reverse.each_char.with_index do |char, index|
tmp = char.to_i * based**index
result += tmp
end
result rescue 0
end

Answer

I suspect you're overthinking this. Since char can only be one of ten different strings, just make a lookup table as a hash:

C_TO_I = {
  "0" => 0, "1" => 1, "2" => 2, "3" => 3, 
  "4" => 4, "5" => 5, "6" => 6, "7" => 7,
  "8" => 8, "9" => 9
}

Then just replace char.to_i in your code with C_TO_I[char]. To demonstrate:

char = "7"
p C_TO_I[char]
# => 7
Comments