Post navigation

15 thoughts on “Ruby shovel operator: What the?!”

In line 2 you create a pointer to the original original string, not a new object. So both hi and original_string point to the same thing. Any changes made via hi or original_string will affect the same underlying object.

Prolly should relax, but the important thing is that all variables are just pointers to something. You can get a new object based on a current one via clone or dup. See irb fun below:
>> a = "Angela"
=> "Angela"
>> b = a
=> "Angela"
>> b < "Angela is learning ruby!"
>> puts a, b
Angela is learning ruby!
Angela is learning ruby!
=> nil

That’s not all the truth.
There are 3 types of strings at ruby runtime:
- Heap strings (that has pointers to malloc’ed heap memory).
- Shared strings (str1 = str2; str1.object_id == str2.object_id;). It also has pointers to malloc’ed heap memory.
- Embedded strings (those stores the string data inside a char array within itself).
When you use the shovel operator with a Shared string, it follows the pointer to the string data stored in heap and changes it. But when you use the += operator, it kills the Shared string and creates a new one, Heap or Embedded depending on the length of it.

Ruby String object is different than the String in language like Java. One thing to notice is Ruby String is mutable.

In Java, if we have:

String a=”Hello”;
String b=a;
String c=b + ” World”;

We will have the following output:
Hello //b
Hello World //c

The “+” operator returns a new instance of String because String is immutable.

In Ruby, since String is mutable, any variable that is pointing to the same String will be effected. This design is consistent with other objects in Ruby. If you want a Ruby object to be immutable, we can use String#frozen to prevent it from being changed.

If you step back and don’t think so hard (or with the biases of other languages), why would you expect any different outcome?
original_string = “Hello, ”
hi = original_string
there = “World”
hi << there

You are appending ‘there’ to ‘hi’ and it stands to reason that you end up with the two strings as “Hello, World”

Maybe you were expecting Ruby to be more difficult?

What I have learned — and attempt to imitate — is that Ruby code should be obvious and comfortable.

And we don’t have a very monopoly. We have business. There’s a difference.
Don’t get worried about people stealing your thinking. If your ideas are any good, you need to ram them down people’s throats.