在使用 `to_i` 或 `to_f` 之前是否有必要使用 'chomp'? [英] Is it ever necessary to use 'chomp' before using `to_i` or `to_f`?

查看:47
本文介绍了在使用 `to_i` 或 `to_f` 之前是否有必要使用 'chomp'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到人们使用以下代码:

I see people use the following code:

gets.chomp.to_i

gets.chomp.to_f

我不明白为什么,当这些行的结果总是与 gets 之后没有 chomp 时相同.

I don't understand why, when the result of those lines are always the same as when there is no chomp after gets.

gets.chomp.to_i 真的有必要,还是 gets.to_i 就够了?

Is gets.chomp.to_i really necessary, or is gets.to_i just enough?

推荐答案

不需要使用chomp方法,因为:

There is no need to use chomp method because:

String#chomp 返回一个新的字符串,其中给定的记录分隔符从 str 的末尾(如果存在)删除.如果 $/ 没有改变默认的 Ruby 记录分隔符,那么 chomp 也会删除回车符(即它会删除\n"、\r",和\r\n").以下是一些示例.

String#chomp returns a new String with the given record separator removed from the end of str (if present). If $/ has not been changed from the default Ruby record separator, then chomp also removes carriage return characters (that is it will remove "\n", "\r", and "\r\n"). Here are some examples.

String#to_f 返回将 str 中的前导字符解释为浮点数的结果.超出有效数字末尾的无关字符将被忽略.如果 str 的开头没有有效数字,则返回 0.0.此方法永远不会引发异常.以下是 to_f 的一些示例.

String#to_f returns the result of interpreting leading characters in str as a floating point number. Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0.0 is returned. This method never raises an exception. Here are some examples for to_f.

这篇关于在使用 `to_i` 或 `to_f` 之前是否有必要使用 'chomp'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆