Ruby String Concatenation

Ran in to a bug tonight.  See it?

def display_value
display_value = notes.blank? ? "untitled" : notes
display_value << " (#{ shortcut })" unless shortcut.blank?
display_value
end

Need a hint?  The symptom was the +notes+ field being unexpectedly changed.

+display_value+ is pointed at +notes+. “<<” then goes ahead and changes that value (which both attributes are pointed at), thus both are effectively changed.

So, while it’s nice to avoid the extra String creation with “<<” where possible – sometimes, you’ve just gotta go with the “+=” to clone, then modify.


a and b ending up the same:
>> a = "a"
=> "a"
>> b = a
=> "a"
>> b << "asomething"
>> a.object_id == b.object_id
=> true


and different:
>> a = "a"
=> "a"
>> b = a
=> "a"
>> b += "something"
=> "asomething"
>> a.object_id == b.object_id
=> false

Advertisements

Leave a comment

Filed under rails, Ruby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s