Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'd like an explanation of a behavior in Ruby that I ran across in the Koans

Tags:

ruby

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
like image 498
Nathan C. Tresch Avatar asked Feb 02 '12 00:02

Nathan C. Tresch


2 Answers

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.

like image 166
nornagon Avatar answered Dec 01 '22 09:12

nornagon


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? .

like image 25
Karl Knechtel Avatar answered Dec 01 '22 08:12

Karl Knechtel