Reputation: 948
So is it just the shovel operator that modifies the original string? Why does this work, it looks like:
hi = original_string
is acting like some kind of a pointer? Can I get some insight as to when and how and why this behaves like this?
def test_the_shovel_operator_modifies_the_original_string
original_string = "Hello, "
hi = original_string
there = "World"
hi << there
assert_equal "Hello, World", original_string
# THINK ABOUT IT:
#
# Ruby programmers tend to favor the shovel operator (<<) over the
# plus equals operator (+=) when building up strings. Why?
end
Upvotes: 8
Views: 631
Reputation: 61527
is acting like some kind of a pointer
It's called reference semantics. As in Python, Ruby's variables refer to values, rather than containing them. This is normal for dynamically typed languages, as it's much easier to implement the "values have type, variables don't" logic when the variable is always just a reference instead of something that has to magically change size to hold different types of values.
As for the actual koan, see Why is the shovel operator (<<) preferred over plus-equals (+=) when building a string in Ruby? .
Upvotes: 3
Reputation: 15821
In ruby, everything is a reference. If you do foo = bar
, now foo
and bar
are two names for the same object.
If, however, you do foo = foo + bar
(or, equivalently, foo += bar
), foo
now refers to a new object: one that is the result of the computation foo + bar
.
Upvotes: 9
Reputation: 40333
A string is just a sequence os characters, the << operator allows you to add more characters to this sequence. Some languages have immutable strings, like Java and C#, others have mutable strings, like C++, there isn't anything wrong about that, it's just something the language designers felt that was necessary.
In Java, when you need to create a large string by merging many smaller strings, you would first use a StringBuilder and then at the end build a real string out of it. In Ruby you can just keep on using << to add more characters to that string and that's it.
The main difference is that using << is much faster than "one_string + other_string" because the + operator generates a new string instead of appending to one_string.
Upvotes: 2