给定一个像这样的字符串对象:
twohundred = "200"
Run Code Online (Sandbox Code Playgroud)
做的有什么区别:
Integer(twohundred) #=> 200
Run Code Online (Sandbox Code Playgroud)
和:
twohundred.to_i #=> 200
Run Code Online (Sandbox Code Playgroud)
有什么区别吗?是否建议在另一个中使用其中一个?
pju*_*ble 49
Integer(num)ArgumentError如果num不是有效整数,则会抛出异常(您可以指定基数).
num.to_i 将尽可能多地进行转换.
例如:
"2hi".to_i
#=> 2
Integer("2hi")
#=> throws ArgumentError
"hi".to_i
#=> 0
Integer("hi")
#=> throws ArgumentError
"2.0".to_i
#=> 2
Integer("2.0")
#=> throws ArgumentError
Run Code Online (Sandbox Code Playgroud)