请告诉我Ruby中的函数,它可以完成以下任务:
发布于 2013-03-30 17:56:48
我喜欢numbers_and_words
宝石。
require 'numbers_and_words'
ruby 2.0.0> 15432.to_words
=> "fifteen thousand four hundred thirty-two"
发布于 2013-03-30 16:31:45
看一看Linguistics宝石。安装时:
gem install linguistics
然后跑:
require 'linguistics'
Linguistics.use(:en) #en for english
5.en.numwords #=> "five"
这对你扔给它的任何数字都是有效的。还值得一提的是,语言学目前只包括一个英语模块,所以如果你需要i18n,就不要使用它。
发布于 2013-03-30 18:15:51
我记得在这上面写了一个递归的解决方案。如果不想使用任何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
https://stackoverflow.com/questions/15720725
复制相似问题