Is it ever necessary to use 'chomp' before using `to_i` or `to_f`?

前端 未结 3 559
忘掉有多难
忘掉有多难 2021-01-04 14:14

I see people use the following code:

gets.chomp.to_i

or

gets.chomp.to_f

I don\'t understand why, when the

相关标签:
3条回答
  • 2021-01-04 14:54

    There is no need to use chomp method because:

    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 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.

    0 讨论(0)
  • 2021-01-04 15:07

    From the documentation for 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 behaves the same way, excluding, of course, the base numbers.

    Extraneous characters past the end of a valid number are ignored, this would include the newline. So there is no need to use chomp.

    0 讨论(0)
  • 2021-01-04 15:12

    It is my opinion that it works the same either way, so there is no need for the chomp after gets if you are going to immediately do to_i or to_f.

    In practice, I have never seen an error raised or different behavior because of leaving chomp out of the line.

    I find it is distracting, when I see it used in answers, and there is absolutely no need for it. It doesn't add to a "style", and it is, as @TheTinMan states, wasted CPU cycles.

    0 讨论(0)
提交回复
热议问题