What is the canonical way to trim a string in Ruby without creating a new string?
ruby, string
Solution
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.
Update: This is output from `irb` to demonstrate:
>> @title = "abc"
=> "abc"
>> @title.strip!
=> nil
>> @title
=> "abc"
>> @title = " abc "
=> " abc "
>> @title.strip!
=> "abc"
>> @title
=> "abc"
Problem
This is what I have now - which looks too verbose for the work it is doing. ``` @title = tokens[Title].strip! || tokens[Title] if !tokens[Title].nil? ``` Assume tokens is a array obtained by splitting a CSV line. now the functions like strip! chomp! et. all return nil if the string was not modified ``` "abc".strip! # => nil " abc ".strip! # => "abc" ``` What is the Ruby way to say trim it if it contains extra leading or trailing spaces without creating copies? Gets uglier if I want to do `tokens[Title].chomp!.strip!`