如何将整数转换为单词表示?

时间:2013-03-30 16:20:10

标签: ruby

请告诉我Ruby中的功能可以完成以下任务:

  • “0”应该给我文字“零”

  • “5”应该给我文字“五”

  • “6”应该给我文字“六”

5 个答案:

答案 0 :(得分:6)

看看Linguistics宝石。安装时:

gem install linguistics

然后运行:

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

这适用于您投掷的任何数字。还值得一提的是,Linguistics现在只包含一个英语模块,所以如果你需要i18​​n,请不要使用它。

答案 1 :(得分:2)

我喜欢numbers_and_words宝石。

require 'numbers_and_words'

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

答案 2 :(得分:2)

我记得写过一个递归的解决方案。如果不想使用任何宝石,请尝试一下:)。

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

答案 3 :(得分:1)

在google上搜索humanize gem,或者你可以使用这样的哈希:

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

然后访问相应的文本:

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

答案 4 :(得分:0)

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