![](/img/trans.png)
[英]Ruby: How do I convert a string (ARGV) representation of integers and ranges to an array of integers
[英]How to convert integers to their word representation?
請告訴我Ruby中的功能可以執行以下任務:
“0”應該給我文字“零”
“5”應該給我文字“五”
“6”應該給我文字“六”
看一下Linguistics寶石。 安裝時間:
gem install linguistics
然后運行:
require 'linguistics'
Linguistics.use(:en) #en for english
5.en.numwords #=> "five"
這適用於您拋出的任何數字。 還值得一提的是,Linguistics現在只包含一個英語模塊,所以如果你需要i18n,請不要使用它。
我喜歡numbers_and_words
gem。
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
在google上搜索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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.