[ruby] 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!

This question is related to ruby string

The answer is


I think your example is a sensible approach, although you could simplify it slightly as:

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

Alternative you could put it on two lines:

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

Btw, now ruby already supports just strip without "!".

Compare:

p "abc".strip! == " abc ".strip!  # false, because "abc".strip! will return nil
p "abc".strip == " abc ".strip    # true

Also it's impossible to strip without duplicates. See sources in string.c:

static VALUE
rb_str_strip(VALUE str)
{
    str = rb_str_dup(str);
    rb_str_strip_bang(str);
    return str;
}

ruby 1.9.3p0 (2011-10-30) [i386-mingw32]

Update 1: As I see now -- it was created in 1999 year (see rev #372 in SVN):

Update2: strip! will not create duplicates — both in 1.9.x, 2.x and trunk versions.


If you have either ruby 1.9 or activesupport, you can do simply

@title = tokens[Title].try :tap, &:strip!

This is really cool, as it leverages the :try and the :tap method, which are the most powerful functional constructs in ruby, in my opinion.

An even cuter form, passing functions as symbols altogether:

@title = tokens[Title].send :try, :tap, &:strip!

If you are using Ruby on Rails there is a squish

> @title = " abc "
 => " abc " 

> @title.squish
 => "abc"
> @title
 => " abc "

> @title.squish!
 => "abc"
> @title
 => "abc" 

If you are using just Ruby you want to use strip

Herein lies the gotcha.. in your case you want to use strip without the bang !

while strip! certainly does return nil if there was no action it still updates the variable so strip! cannot be used inline. If you want to use strip inline you can use the version without the bang !

strip! using multi line approach

> tokens["Title"] = " abc "
 => " abc "
> tokens["Title"].strip!
 => "abc"
> @title = tokens["Title"]
 => "abc"

strip single line approach... YOUR ANSWER

> tokens["Title"] = " abc "
 => " abc "
> @title = tokens["Title"].strip if tokens["Title"].present?
 => "abc"

There's no need to both strip and chomp as strip will also remove trailing carriage returns - unless you've changed the default record separator and that's what you're chomping.

Olly's answer already has the canonical way of doing this in Ruby, though if you find yourself doing this a lot you could always define a method for it:

def strip_or_self!(str)
  str.strip! || str
end

Giving:

@title = strip_or_self!(tokens[Title]) if tokens[Title]

Also keep in mind that the if statement will prevent @title from being assigned if the token is nil, which will result in it keeping its previous value. If you want or don't mind @title always being assigned you can move the check into the method and further reduce duplication:

def strip_or_self!(str)
  str.strip! || str if str
end

As an alternative, if you're feeling adventurous you can define a method on String itself:

class String
  def strip_or_self!
    strip! || self
  end
end

Giving one of:

@title = tokens[Title].strip_or_self! if tokens[Title]

@title = tokens[Title] && tokens[Title].strip_or_self!

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

It's entirely possible i'm not understanding the topic, but wouldn't this do what you need?

" success ".strip! || "rescue" #=> "success"
"failure".strip! || "rescue" #=> "rescue"

My way:

> (@title = " abc ").strip!
 => "abc" 
> @title
 => "abc" 

If you want to use another method after you need something like this:

( str.strip || str ).split(',')

This way you can strip and still do something after :)