Monday, April 27, 2009

Ruby Chop vs Chomp

When you receive user input from textareas or console input you may get some newline characters. One way to remove newline characters is the String#chop method, it will remove any trailing newline or carriage return characters “\r\n”. But it’s tricky. Because here it works like it’s suppose to.

full_name = "My Name is Ravikanth\r\n" 

full_name.chop! # => "My Name is
Ravikanth"

Now if you run chop and there are no newline characters.

puts full_name    #=> "My Name is Ravikanth"

full_name.chop! #=> "My Name is
Ravikant"

Disaster Strikes!

That’s why there is chomp.

puts full_name       #=> "My Name is Ravikanth\r\n"

full_name.chomp! #=> "My Name is
Ravikanth"
full_name.chomp! #=> "My Name is
Ravikanth"

So chomp is our recommended way of removing trailing newline characters.


1 comment: