Why does chomp allow chaining but chomp! doesn’t? For example:
"HELLO ".chomp.downcase
#> hello
"HELLO ".chomp!.downcase
#> nil
Another interesting example:
"100 ".chomp.to_i
#> 100
"100 ".chomp!.to_i
#> 0
Any ideas why this behavior occurs on the string, and why nil.to_i returns 0?
From the fine manual:
and for
chomp!:So neither
chompnorchomp!do what you think they do. Observe:So neither one cares about trailing spaces unless you tell them to, they just strip off trailing EOLs by default.
'100 '.chomp!returnsnilbecause that’s what the documentation says it does. No substitution was made so it returnsnil.Why does
nil.to_igive you zero? Well, from the fine manual:That doesn’t leave much room for ambiguity or interpretation.
I think you’re actually after the
stripfamily of methods rather thanchomp:String#lstripString#lstrip!String#rstripString#rstrip!String#stripString#strip!Those remove whitespace from the string.