将字符串数字(以字格式)转换为整数ruby

时间:2012-11-26 12:16:24

标签: ruby

如果你有一个字符串ten,是否可以在Ruby中将其转换为整数10? (也许在铁轨?)

我重视tryruby.org的开发人员,在他们的教程here中,它特别说“to_i将事物转换为整数(数字。)”我想知道为什么他们没有说“to_i将STRINGS转换为整数(数字。)“

哪些变量类型可以从它们的类型转换为整数?

4 个答案:

答案 0 :(得分:9)

查看this gem处理字对数转换。

自述文件:

require 'numbers_in_words'
require 'numbers_in_words/duck_punch'

112.in_words
#=> one hundred and twelve
"Seventy million, five-hundred and fifty six thousand point eight nine three".in_numbers
#=> 70556000.893

答案 1 :(得分:2)

我将如何做到。

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

用于测试;

n_to_s(rand(9999))

答案 2 :(得分:1)

由于String#to_i只选择数字字符,因此无法按照您想要的方式工作。可能有一些与此相关的Rails方法,但肯定不会有方法名称to_i,因为它的行为会与String#to_i的原始意图冲突。

Strings不仅to_i NilClassTimeFloatRational"3".to_i #=> 3 "".to_i #=> 0 nil.to_i #=> 0 Time.now.to_i #=> 1353932622 (3.0).to_i #=> 3 Rational(10/3).to_i #=> 3 (也许还有其他一些类别)也会这样做。

{{1}}

答案 3 :(得分:-2)

这是一个简单的字符串查找到它们的数字等价物:

str_to_int_hash = {
  'zero'  => 0,
  'one'   => 1,
  'two'   => 2,
  'three' => 3,
  'four'  => 4,
  'five'  => 5,
  'six'   => 6,
  'seven' => 7,
  'eight' => 8,
  'nine'  => 9,
  'ten'   => 10
}

str_to_int_hash['ten']
=> 10

显然还有许多其他缺失的条目,但它说明了这个想法。

如果你想从一个数字转到字符串,这就是起点:

int_to_str_hash = Hash[str_to_int_hash.map{ |k,v| [v,k] }]
int_to_str_hash[10]
=> "ten"