Thursday, February 7, 2013

Separate Comma Done!

Happy to say that I finally go the separate_comma method in the DBC exercises this time. The last method I wrote was able to beat the specs, but was hard coded in and I was not happy about it, but it was the only thing standing in my way from finishing so I made a deal with the coding devil with and IOU that I just finished ;-). So before I was trying to iterate over an array and was executing this poorly, but the initial logic was sound. I know that I had to reverse the string in the beginning in order to count up because the comma's come every 3 regardless.

From there I was able to do a while loop that used the .insert method in order to insert a comma every 4th character. Why every 4 you might ask, there is an answer for that. You have to do it every 4th because after you add a comma in that becomes another character in the string so you have "000," instead of "000" and as you count up it will have to be "4,8,12..." instead of "3,6,9..." too keep up with the loop. After I was done with the while loop to insert commas into the string I thoroughly tested it to make sure there were no bugs in the code....there were. It turns out that this loop would put a comma at the end of the string every time so at the end when you reversed it back you would have ",10,000" instead of "10,000". This was a simple fix with the .slice! method and voila, separate comma is complete!


  1. def separate_comma(x)
  2.     string = x.to_s.reverse
  3.     len = -1
  4.     while len < string.length - 1
  5.         string.insert(len, ",")
  6.         len +4
  7.     end
  8.     string.slice!(string.length-1)
  9.     result = string.reverse
  10.     result
  11. end

No comments:

Post a Comment