1

I am trying to make an RPN calculator. I have to implement my own .to_i and .to_f method. I cannot use send, eval, Float(str) or String(str) method. The assignment is done, but I still want to know how to implement it.

The input: atof("255.25") as string type
Output: 255.55 as float type

Here is my code for atoi

ASCII_NUM_START = 48 # start of ascii code for 0

def ascii_to_i(int_as_str)

array_ascii = int_as_str.bytes
converted_arr = array_ascii.map {|ascii| ascii - ASCII_NUM_START }
converted_arr.inject { |sum, n| sum * 10 + n }
end

def ascii_to_f(float_as_str)
???
end

Community
  • 1
  • 1

2 Answers2

1

I got it working doing the following (and utilizing your ascii_to_i function).

ASCII_NUM_START = 48 # start of ascii code for 0 


def ascii_to_i(int_as_str) 

  array_ascii = int_as_str.bytes 
  converted_arr = array_ascii.map {|ascii| ascii - ASCII_NUM_START } 
  converted_arr.inject { |sum, n| sum * 10 + n } 
end 

def ascii_to_f(float_as_str) 
  int_split = float_as_str.split(".")
  results = []
  int_split.each { |val| results << ascii_to_i(val) }
  results[0] + (results[1] / (10.0 ** int_split.last.length))
end
Anthony
  • 15,435
  • 4
  • 39
  • 69
0

I can see you have made a reasonable effort at ascii_to_i.

The code for ascii_to_f can be similar, and in addition you will need to divide the result by the number of decimal places that you have processed.

Probably the easiest adaptation is:

  • find the position of the . character (ASCII code 46) in the String, save that as a variable
  • remove the . character (ASCII code 46) from your array of bytes
  • calculate the Integer value from the array of bytes as before
  • divide by 10.0 (must be a Float) to the power of (the length of the remaining array minus the position you found the . in).

I am not giving code, because it is an assignment. See if you can figure out the correct syntax, looking at documentation for the Array class for finding the position of a specific value, for deleting a specific value, and for getting length of the array.

Neil Slater
  • 26,512
  • 6
  • 76
  • 94
  • thank you, this helps. I didn't turn it in time for the assignment, but I wanted to learn how to do it. I think the "." split is helpful. I'll try your pseudocode out! – the_answer_is_xyz Jul 07 '14 at 17:43