John Oggy
John Oggy

Reputation: 319

How to convert integers to their word representation?

Please, tell me the function in Ruby which can do the below task:

Upvotes: 3

Views: 2364

Answers (5)

shayonj
shayonj

Reputation: 910

I remember writing a recursive solution on this. Try it out if dont want to use any gem :).

class Integer
  def in_words
    words_hash = {0=>"zero",1=>"one",2=>"two",3=>"three",4=>"four",5=>"five",6=>"six",7=>"seven",8=>"eight",9=>"nine",
                    10=>"ten",11=>"eleven",12=>"twelve",13=>"thirteen",14=>"fourteen",15=>"fifteen",16=>"sixteen",
                     17=>"seventeen", 18=>"eighteen",19=>"nineteen",
                    20=>"twenty",30=>"thirty",40=>"forty",50=>"fifty",60=>"sixty",70=>"seventy",80=>"eighty",90=>"ninety"}

    if words_hash.has_key?(self) 
      words_hash[self]
    elsif self >= 1000
      scale = [""," thousand"," million"," billion"," trillion"," quadrillion"]
      value = self.to_s.reverse.scan(/.{1,3}/)
        .inject([]) { |first_part,second_part| first_part << (second_part == "000" ? "" : second_part.reverse.to_i.in_words) }
      (value.each_with_index.map { |first_part,second_part| first_part == "" ? "" : first_part + scale[second_part] }-[""]).reverse.join(" ")

    elsif self <= 99
       return [words_hash[self - self%10],words_hash[self%10]].join(" ")
    else
      words_hash.merge!({ 100=>"hundred" })
      ([(self%100 < 20 ? self%100 : self.to_s[2].to_i), self.to_s[1].to_i*10, 100, self.to_s[0].to_i]-[0]-[10])
        .reverse.map { |num| words_hash[num] }.join(" ")
    end
  end
end

Upvotes: 2

AGS
AGS

Reputation: 14498

I like the numbers_and_words gem.

require 'numbers_and_words'

ruby 2.0.0> 15432.to_words
=> "fifteen thousand four hundred thirty-two"

Upvotes: 2

A human being
A human being

Reputation: 1220

Search on google for humanize gem or you can just use a hash like this:

number_to_word = { 1 => "One", 2 => "Two", 3 => "Three", ...}

then access corresponding text like this:

text = number_to_word[1] # for accessing value of 1

Upvotes: 1

Nir Alfasi
Nir Alfasi

Reputation: 53535

mapper = {0 => "zero", 1 => "one", 2 => "two",... }
# and now you can use mapper to print the text version of a numer
print mapper[2]

Upvotes: 0

Linuxios
Linuxios

Reputation: 35803

Take a look at the Linguistics gem. Install with:

gem install linguistics

And then run:

require 'linguistics'
Linguistics.use(:en) #en for english
5.en.numwords #=> "five"

This will work for any number you throw at it. It's also worth mentioning that Linguistics only includes a module for English right now, so don't use it if you need i18n.

Upvotes: 6

Related Questions