My exercise was to take a string of numbers, such as "1234" and return them as an integer 1234. However, I wasn't allowed to use
def convert(int) x = 0 array = int.split('') array.each.with_index do |y, i| x = (x + (y.hex)) x = x * 10 unless i == array.length-1 end return x end p convert('1234') p convert('3225') p convert('4321') == 4321 p convert('570') == 570
When I first started on this exercise, I wondered if I would be able to convert the String into a binary, octal, or other type of representation. Then, take that representation and convert it into integers.
Unfortunately, using #pack and #unpack resulted in more strings, and I couldn't really understand some of the methods that I could use with pack/unpack. Right now I don't have much knowledge in programming, so I couldn't really figure out how to take those strings and parse them into the Integers that I wanted. (My math kinda sucks too...)
Then I read about hex some more and realized that the hex representation of numbers 0-9 are the same as the integers! So I simply converted each number to a hex, added it to a variable and multiplied it by 10 with each iteration of the loop.
I know there's probably a better way to do this, but this is what I came up with.
I know another way (and possibly simpler) is to make a hash of 10 numbers, 0 - 9, with the keys being the Stringed numbers and their values being Integers, then iterating through that.
Anyways, please let me know what you think of my code and my thought process, and suggest what you can.