问题描述
我正在学习RUBY,但我不知道如何将字符串转换为整数。例如字母的奇数或偶数,等等。
解决方法
要将字符串转换为整数,请使用#to_i
'12'.to_i
=> 12
一旦它是整数,就可以测试奇数或偶数...
'12'.to_i.odd?
=> false
'12'.to_i.even?
=> true
对于整数的长度(位数),您可以计算位数...
'12'.to_i.abs.digits.count
=> 2
,
该问题确实声明了整数,但是某些字符串可以表示浮点数或有理数甚至十六进制数
'2'.to_i => 2 # Fixnum
'2.01'.to_f => 2.01 # Float
'2'.to_r => (2/1) # Rational
'2'.to_c => (2+0i) # Complex
to_i
假定以10为基数的表示形式,但是Ruby允许您更改它。
'2'.to_i(base=2) => 0 # Fixnum
to_i
也可以处理十六进制的“数字”
`b`.to_i(base=16) => 11 # Fixnum
to_i
将从字符串开头转换所有数字字符,直到可迭代对象遇到无法强制转换为整数类型的字符。
'12a'.to_i => 12 # Fixnum
,
将字符串转换为整数:例如my_str.to_i
"foo".to_i # 0
"132".to_i # 132
"132.4".to_i # 132
"foo132".to_i # 0
"132foo".to_i # 132
要查找字符串中的字符是否为奇数或偶数:my_str.length.odd?
或my_str.length.even?
,例如:
"foo".length.odd? # true
"132".length.odd? # true
"foo".length.even? # false
"132".length.even? # false
另请参见: