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

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!

9 Answers
9

Leave a Comment