Convert string numbers( in word format) to integer ruby

后端 未结 4 2000
没有蜡笔的小新
没有蜡笔的小新 2021-01-24 18:43

If you have a string ten, is it possible to convert it to an integer 10 in Ruby? (maybe in rails?)

I value the developers at tryruby.org, and i

4条回答
  •  悲&欢浪女
    2021-01-24 18:54

    How I would have done it.

    def n_to_s(int)
    
        set1 = ["","one","two","three","four","five","six","seven",
             "eight","nine","ten","eleven","twelve","thirteen",
             "fourteen","fifteen","sixteen","seventeen","eighteen",
             "nineteen"]
    
        set2 = ["","","twenty","thirty","forty","fifty","sixty",
             "seventy","eighty","ninety"]
    
        thousands = (int/1000)
        hundreds = ((int%1000) / 100)
        tens = ((int % 100) / 10)
        ones = int % 10
        string = ""
    
        string += set1[thousands] + " thousand " if thousands != 0 if thousands > 0
        string += set1[hundreds] + " hundred" if hundreds != 0
        string +=" and " if tens != 0 || ones != 0 
        string = string + set1[tens*10+ones] if tens < 2
        string += set2[tens]
        string = string + " " + set1[ones] if ones != 0     
        string << 'zero' if int == 0    
        p string
    end
    

    for the purpose of testing;

    n_to_s(rand(9999))
    

提交回复
热议问题