String Mathematics in Ruby

Here is a problem => What is 5 plus 13? Pretty easy right? Well, how do we go about getting a computer to read that string? If the question is What is 5 plus 13 minus 7 are we going to read that in sequence or by order of operations? Let’s say we’ll do this in sequence and kick this off.

First it might behoove us to Translate this string to a more simplified/more computer friendly string.

If we iterate through each word, cast away irrelevant words, look for key words such as plus and minus, and then finally grab out the integers, we might end up with a string like “5 :+ 13” or “5 :+ 13 -: 7”. What is the :+ or :- ? They are symbols which we can pass around later. More on that! But you might be able to see that this is a bit more computer friendly.

We go through each word and determine first off if it is actually a number by referencing the method alphabet_check.

Bad indentation aside, this checks to see if the word passed in is in fact a word

If it is a number, we are going to push that into our variable calculation. If we detect those special arithmetic words we will instead push in symbols representing that type of function. We will harness those symbols by the ruby Enumerable Reduce. If we want to add up an array of numbers like [“1”,”2",”3"] we can either => given_array.reduce(0) {|acc, num| acc + num} or more simply => given_array.reduce(:+). If you are wondering whether or not we can do => given_array.reduce(:-) or given_array.reduce(:/), well I’d like to inform you that we can! It might be more apparent as to why we are translating this string by using these symbols now.

As we go through that translated string, anytime we hit a symbol we are going to trigger a certain calculation as defined by computer(calculation, index, :/). We are going to pass in the translated array, the index that triggered the calculation and what arithmetic calculation that was.

The computer basically takes in the translated mathematical problem and sees wether or not to operate on the char before and after the symbol in the case of the empty calculation or just take the previous calculation and add on one more character and then operate as defined by the non_empty_calculation.

@calculations is an instance variable defined in initialize