Recently I tried to create a ruby method that formatted a number to a string but comma separating large numbers.
For example: 100000 should result in 100,000 and 352456745 in 352,456,745
My first monstrous attempt was:
def number_to_string(number) num_str = number.to_s array_str_num = num_str.to_s.split(//) result =  array_str_num.each_with_index do |value, index| result << value result << ',' if index % 3 == 0 end p result.join end
But this returned “1,000,00” for 100000 which is NOT the end result I envisioned.
Then after twenty minutes of frustration, I left my room to quench my thirst. While I was drinking a nice cold beer my subconscious kicked in and I pictured the solution right away. I actually had to reverse the array of stringed numbers and add one to index to place the comma in the position that I wanted.
def number_to_string(number) result =  # reverse the string and then split it number.to_s.reverse.split(//).each_with_index do |value, index| result << value #add 1 to index to get the comma in the correct position result << ',' if (index + 1) % 3 == 0 end result.join('').reverse end number_to_string(100000) #=> 100,000 number_to_string(352456745) #=> 352,456,745
Yes! It worked now. The code is ugly as fuck but it gave me the expected result. A friend once told me that if I was ever totally stuck at a problem, then I should reverse the data. When I was studying for the SAT for example, one of strategies for vocabulary retention I used was to say a word backwards out loud a few times. I have no idea why this tactic works, but apparently it helps programmers too.
So if you happen to feel hopelessly lost because of a hard problem, try reversing how you are viewing, approaching, or even reading it. Don’t forget that a cold beer on your side might also do the trick.
Thanks to @caffo for referring me to the problem. Hope we can have a cold beer someday.