title: Number Search Coderbyte Ruby
body: <p>I am solving this problem at coderbyte</p>
  
  <p><strong>Using the Ruby language, have the function NumberSearch(str) take the str parameter, search for all the numbers in the string, add them together, then return that final number. For example: if str is "88Hello 3World!" the output should be 91. You will have to differentiate between single digit numbers and multiple digit numbers like in the example above. So "55Hello" and "5Hello 5" should return two different answers. Each string will contain at least one letter or symbol.</strong></p>
  
  <p>My first attempt to solve the number search problem results in the code below. However, after submitting it, it did not work for the case of <code>"1 2 3 4 k10"</code> which is obvious after comparing my code.</p>
  
  <p>The solution would have been more elegant had I used regular expression and splitted it based on non-digit character, and then added each element in the splitted array, but I wanted to try solving using the long way. </p>
  
  <p>How would this code be fixed so that it also works for the case of <code>"1 2 3 4 k10"</code>? the intent of my code is to search all the elements in the string and if it sees more digit in a block of string, it would add up the string. If the next string is not a digit then it resets the <code>num_str</code>. I would get an array of number string which is <code>num_arr</code>.</p>
  
  <p>My original codes:</p>
  
  <pre><code>def NumberSearch(str)
    num_str = ""    #store numbers with more than one digit
    num_arr = []    #number storage
    sum = 0
    i = 0
    while i&lt;=str.length
      if str[i,1].to_i&gt;0
        num_str = num_str + str[i,1]
      elsif str[i,1].to_i == 0    #str[i].to_i is 0
        num_arr &lt;&lt; num_str.to_i
        num_str = ""    #reset string number
      end
  
      i += 1
    end
  
    num_arr.each do |x|
      sum = sum + x
    end
    return sum
  
  end
  </code></pre>
  
  <p>Editted:</p>
  
  <p>Following Beartech's suggestion below, I updated the code. I use string <code>.include?</code> method instead of the array <code>.include?</code> method. Also the method name came from Coderbyte. Using capital letter in method name is un-rubyist.</p>
  
  <pre><code>def NumberSearch(str) 
    num_str = ""    #store numbers with more than one digit
    num_arr = []    #number storage
    sum = 0
    i = 0
    #str&lt;&lt;"required!"  #add nondigit character for code to work
    while i&lt;str.length
      if "0123456789".include? str[i,1]
        num_str = num_str + str[i,1]
      elsif   #note the "required" was added earlier because of this section here
        num_arr &lt;&lt; num_str.to_i   
        num_str = ""    #reset string number
      end
  
      i += 1
    end
    num_arr.each do |x|
      sum = sum + x
    end
    return sum
  
  end
  </code></pre>