ruby 代码
- x = "123".to_i # 123
- y = Integer("123") # 123
- x = "junk".to_i # 0
- y = Integer("junk") # error
- # 遇到非数字字符时,to_i方法将停止转换, 将Integer将引发错误
- x = "123junk".to_i # 123
- y = Integer("123junk") # error
- # 允许字符串的开头和末尾有空白
- x = " 123 " # 123
- y = Integer(" 123 ") # 123
本文详细介绍了在Ruby中如何使用to_i方法和Integer类将字符串转换为整数。探讨了当遇到非数字字符时两种方法的不同行为,to_i会停止转换并返回已解析的部分,而Integer则会引发错误。
1177

被折叠的 条评论
为什么被折叠?



