DEV Community

Jennifer Konikowski
Jennifer Konikowski

Posted on

Translating Integers Into An English String in Ruby

I'm a huge dork. I was fiddling around on repl.it to see if I could use it in next year's AP CS class (hey go volunteer with TEALS!) and I stumbled upon this script from a year ago. Don't judge me too harshly! I don't even know what I was doing or why. After seeing the state it was in, I could not leave it alone. And apparently, I am in a better headspace now because I was able to refactor it fairly quickly and get it into a much better state. I did this heavily utilizing constants and recursion, but I'd be interested to see how others would solve this.

Here is the code if you don't want to bother with the repls:

Top comments (8)

Collapse
 
andy profile image
Andy Zhao (he/him)

Nice refactor 👌

Btw, we have a hidden -- as in, we forgot to put it in the editor guide -- repl.it Liquid tag if you want to use it:

{% replit @jmkoni/englishnumberold %}

{% replit @jmkoni/Englishnumber %}

Looks a bit weird in the comment preview, but it works in actual comments and articles. :)

Collapse
 
jennifer profile image
Jennifer Konikowski

Thanks Andy! I'll definitely be using that in the future 😃

Collapse
 
thorstenhirsch profile image
Thorsten Hirsch

That's a nice task.
Here's an updated version of Jennifer's code with some small bugfixes, which can be run as a script (./number_printer.rb 123).

Collapse
 
jennifer profile image
Jennifer Konikowski

Thank you, Thorsten! I like the update to make it take in args from the command line.

Collapse
 
jakebman profile image
jakebman

English is just an instance of a language.

Languages have different ways of doing this.

For instance, there's no seventy in French. The seventies are written as sixty and thirteen.

Then you realize that's why libraries exist and find one that suits your needs.

Collapse
 
jennifer profile image
Jennifer Konikowski

Yes. But this is just an exercise for fun?

Collapse
 
databasesponge profile image
MetaDave 🇪🇺

And a damn good exercise it is too.

We needed to translate integers from 0 to 100 into words for our system, and looked at a few gems, and thought about the logic, and then said "f*ck it" and just created a YAML file:

0: zero
1: one
2: two
...

Problem solved, and testing was pretty straightforward too!

Thread Thread
 
jennifer profile image
Jennifer Konikowski

I love it. Sometimes, if you have a limit like that, writing it out manually can be easier on a quick deadline! Especially if you need to support many languages.