What is the canonical way to trim a string in Ruby without creating a new string?

I guess what you want is:

@title = tokens[Title]
@title.strip!

The #strip! method will return nil if it didn’t strip anything, and the variable itself if it was stripped.

According to Ruby standards, a method suffixed with an exclamation mark changes the variable in place.

Hope this helps.

Update: This is output from irb to demonstrate:

>> @title = "abc"
=> "abc"
>> @title.strip!
=> nil
>> @title
=> "abc"
>> @title = " abc "
=> " abc "
>> @title.strip!
=> "abc"
>> @title
=> "abc"

Leave a Comment