Using Ruby convert numbers to words?

前端 未结 8 1390
广开言路
广开言路 2020-12-09 19:30

How to convert numbers to words in ruby?

I know there is a gem somewhere. Trying to implement it without a gem. I just need the numbers to words in English for integ

8条回答
  •  生来不讨喜
    2020-12-09 19:54

    I am not quite sure, if this works for you. Method can be called like this.

    n2w(33123) {|i| puts i unless i.to_s.empty?}
    

    Here is the method ( I have not tested it fully. I think it works upto million. Code is ugly, there is a lot of room for re-factoring. )

    def n2w(n)
      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"}
      scale = {3=>"hundred",4 =>"thousand",6=>"million",9=>"billion"}
    
      if words_hash.has_key?n
        yield words_hash[n] 
      else
        ns = n.to_s.split(//)
          while ns.size > 0      
            if ns.size == 2
                yield("and")
                yield words_hash[(ns.join.to_i) - (ns.join.to_i)%10]            
                ns.shift
            end
            if ns.size > 4
              yield(words_hash[(ns[0,2].join.to_i) - (ns[0,2].join.to_i) % 10])
            else
              yield(words_hash[ns[0].to_i]) 
            end
            yield(scale[ns.size])
            ns.shift
          end
        end
    end
    

提交回复
热议问题