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?
I guess what you want is:
@title = tokens[Title]
@title.strip!
The #strip!
method will return nil
if it didnt 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 nil
p abc.strip == abc .strip # true
Also its 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.
What is the canonical way to trim a string in Ruby without creating a new string?
Theres no need to both strip and chomp as strip will also remove trailing carriage returns – unless youve changed the default record separator and thats what youre chomping.
Ollys 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 dont 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 youre 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!