Today I was faced with this old ruby quiz (so I learned) http://rubyquiz.com/quiz25.html. The main idea was to display basic TDD principles, since we did it on a shared screen.
The challenge: Create Ruby code to translate a number to its English language form.
What I really liked about how they presented the exercise is that it was TDD (Test Driven Development) at it's basic, just seeing how you would approach at coding this exercise with the TDD principles.
Now talking about the code, my first version of it was disastrous, I was really nervous. My logic was using some case statements and it made it really hard to refactor or scale.
I researched some and found that there's even a gem that does it for multiple languages:
https://github.com/kslazarev/numbers_and_words
I found this post that I used for the idea of the hashes:
http://raveendran.wordpress.com/2009/05/29/ruby-convert-number-to-english-word/
Here's the code that I thought worked, but then testing more I found that the cases for 11-19 failed for numbers over 100:
This is the code that I think works completely. With the previous example, I realized that I need to operate in groups of 3 digits, because that's the group of hundreds, decimals and units that compose every other group of thousands, millions, billion, trillion, etc. From there just getting each one of the elements and finding and joining the right texts. This is the code:
Have you done this exercise before? Do you think my code works? What would you change? Let's hear your thoughts.
NOTE: My good friend Gustavo Gonzalez got into this too and here is his solution: