Parse sentences and calculate mathematical results
The problem is that you are manipulating text without using Regular Expressions.

Regular expressions are a tool made specifically for text manipulation (search, delete, replace ... ) and are extremely good at their job.

The over-complication you experience comes from the use loops, conditionals and arithmetic to manipulate strings.

Here is a solution using regular expressions:

def text_calculation(text)
  a, b = text.split(/[^0-9]/).reject(&amp;:empty?).map(&amp;:to_i)
  text.include?("gains") ? a + b : a - b
end


First line explanation

text.split(/[^0-9]/)


This splits the text at every character that is not a digit (^ negates and [0-9] means from 0 to 9.

The output is this list:

["", "", "", "", "", "", "", "", "", "", "48", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "4"]


Almost what we want, we just need to remove (reject) the empty strings (empty?):

.reject(&amp;:empty?)


So now we have ["48", "4"] that we must convert to integers before we can do arithmetic on, map applies a function to each item of a list and to_i converts to integer so .map(&amp;:to_i)

Second line explanation

We add if we find "gains" else subtract (condition ? if_true : if_false is the Ternary operator)

.scan

We need to find the parts of the string that match a given regex, given that the regex /\d+\ matches all the subsequent strings of digits.

We must "find all regex matches in ruby", searching Google for such a task lands us on StackOverflow reveals that .scan is exactly what we can use. (The second Stack Overflow example is even about searching digits in a string!) 

def text_calculation(text)
  a, b = text.scan(/\d+/).map(&amp;:to_i)
  text.include?("gains") ? a + b : a - b
end


This code is more direct than splitting and filtering.