如何使用哈希多个键生成值为ruby的组合字符串
发布时间:2020-12-17 01:51:31 所属栏目:百科 来源:网络整理
导读:所以我在下面有这个哈希: a_hash = { "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"
所以我在下面有这个哈希:
a_hash = { "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","00" => "hundred",#not sure this is right "000" => "thousand" #not sure this is right } 可以说我的字符串输入是“99100”. puts "test the hash! Type a number hit enter" test_variable = gets.to_s.chomp puts a_hash[test_variable] 发布一些代码,以便我可以试试.谢谢! 解决方法
简短的回答:不要自己这样做,找到一个适合你的
library.
然而,它可能是一个很酷的运动,它实际上是一个有趣的问题.因此,忽略了不重新发明轮子的最佳实践……你可能不得不以不同的方式对待数百和数千,因为你可以说“二百”,但“二十七”并没有多大意义. 这是我经过严格测试,未经优化的尝试.这是一个概念验证,我很确定我忽略了很多案例.如果您需要更多帮助,请尝试阅读其他人的source code. 首先,我们定义两个哈希值,一个用于数字,一个用于量值(这是不同的,因为它们可以用数字作为前缀以便将它们相乘). class Integer NUMBERS = { 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" } MAGNITUDES = { 100 => "hundred",1000 => "thousand",1000_000 => "million" } end 接下来,定义转换方法. class Integer def to_text return nil if self == 0 if NUMBERS.keys.include? self NUMBERS[self] elsif self < MAGNITUDES.keys.first base = maximum_fitting(NUMBERS,self) [NUMBERS[base],(self - base).to_text].compact * "-" else base = maximum_fitting(MAGNITUDES,self) quo,mod = self.divmod(base) [quo.to_text,MAGNITUDES[base],mod.to_text].compact * " " end end private def maximum_fitting(list,number) list.keys.select { |n| n <= number }.last end end 要使用它: puts 2351.to_text #=> "two thousand three hundred fifty-one" puts 14330132.to_text #=> "fourteen million three hundred thirty thousand one hundred thirty-two" puts 1000000.to_text #=> "one million" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |