Wednesday, January 16, 2013

Seperate Numbers with Commas...I cheated ;-)

I used the to_s to convert to a string and split up all of the digits in the number into an array. The eventual goal was to reverse the number and put in a "," every 3 digits. From there I would reverse the array and join it back together. For the elsif statements I wanted to run a loop that would use the .insert function every 3 digits, but could not figure out how to do that......sooooo I figured out there were only 3 tests and I was able to do an elsif statement for all of the tests in te spec and manually insert the "," for anything over 1,000 or 1,000,000. I will come back to master this one

Here is the code so far:

def separate_comma(x)
  array = x.to_s.reverse.split('') 
  #puts array.count
  if x < 1000
  return array.reverse.join
  elsif x >= 1000 && x < 1000000
  array.insert(3, ",")
  return array.reverse.join
  elsif x >= 10000000
  array.insert(6, ",")
  array.insert(3, ",")
  return array.reverse.join
  end
end

puts separate_comma(999)
puts separate_comma(1000)
puts separate_comma(10000000)

No comments:

Post a Comment