vgoff vgoff - 4 months ago 10
Ruby Question

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

I see people use the following code:

gets.chomp.to_i


or

gets.chomp.to_f


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

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

Answer

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.