请告诉我 Ruby 中可以执行以下任务的函数:
“0”应该给我文本“零”
“5”应该给我文本“5”
“6”应该给我文本“6”
看看语言学宝石。安装:
gem install linguistics
然后运行:
require 'linguistics'
Linguistics.use(:en) #en for english
5.en.numwords #=> "five"
这适用于你扔给它的任何数字。还值得一提的是,Linguistics 目前只包含一个英语模块,所以如果你需要 i18n,请不要使用它。
我喜欢numbers_and_words
宝石。
require 'numbers_and_words'
ruby 2.0.0> 15432.to_words
=> "fifteen thousand four hundred thirty-two"
我记得为此写了一个递归解决方案。如果不想使用任何宝石,请尝试一下 :)。
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
在谷歌上搜索humanize gem,或者你可以使用这样的哈希:
number_to_word = { 1 => "One", 2 => "Two", 3 => "Three", ...}
然后像这样访问相应的文本:
text = number_to_word[1] # for accessing value of 1
mapper = {0 => "zero", 1 => "one", 2 => "two",... }
# and now you can use mapper to print the text version of a numer
print mapper[2]