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

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"


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

Compare:

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

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

static VALUErb_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.


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! || strend

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 strend

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

class String  def strip_or_self!    strip! || self  endend

Giving one of:

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