如果您有一个字符串ten
,是否可以在Ruby中将其转换为整数10
? (也许在轨道上?)将字符串数字(字格式)转换为整数ruby
我看重的是开发人员在tryruby.org和他们的教程here,它具体说“to_i转换为整数(数字)。”我想知道他们为什么不说“to_i将STRINGS转换为整数(数字)“
什么变量类型可以从它们的类型转换为整数?
如果您有一个字符串ten
,是否可以在Ruby中将其转换为整数10
? (也许在轨道上?)将字符串数字(字格式)转换为整数ruby
我看重的是开发人员在tryruby.org和他们的教程here,它具体说“to_i转换为整数(数字)。”我想知道他们为什么不说“to_i将STRINGS转换为整数(数字)“
什么变量类型可以从它们的类型转换为整数?
退房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
由于String#to_i
只挑选数字字符,它不会以您想要的方式工作。可能有一些与之相关的Rails方法,但它肯定不会有方法名称to_i
,因为它的行为将与String#to_i
的原始意图相冲突。
它不仅Strings
有to_i
。 NilClass
,Time
,Float
,Rational
(也许还有其他一些类)也可以。
"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
这是一个简单的字符串查找到他们的数字等效:
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"
虽然这是一个小值的起点,但它并不暗示将其扩展到任意大数量所需的一般性。 – Michael
这就是为什么我说“简单查找”。由于OP没有提到超出简单数字的任何内容,所以这是一个非常令人困惑和问题很少的问题。除此之外,它需要一个更彻底的代码。 –
我怎么会做。
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))
似乎OP意味着'10'到10,''9'到9等:) – 2012-11-26 12:24:52
@slivu OP是问多个问题。我只回答最后一个。 – sawa