gpt4 book ai didi

ruby - 在使用 'chomp' 或 `to_i` 之前是否有必要使用 `to_f` ?

转载 作者:数据小太阳 更新时间:2023-10-29 06:46:50 35 4
gpt4 key购买 nike

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

gets.chomp.to_i

gets.chomp.to_f

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

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

最佳答案

来自 String#to_i 的文档:

Returns the result of interpreting leading characters in str as an integer base base (between 2 and 36). Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0 is returned

String#to_f行为方式相同,当然不包括基数。

超出有效数字末尾的无关字符 将被忽略,这将包括换行符。所以没有必要使用chomp

关于ruby - 在使用 'chomp' 或 `to_i` 之前是否有必要使用 `to_f` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20598679/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com