views:

21

answers:

1

In this example, do the nukes get launched because any changes that you make to buggy_logger get applied to the 'status' string - just like using a copy of a reference to an object -> when you make a change to the copy of the reference, the change gets applied to the underlying object -> that change is, in turn, reflected in any other references to the object. So, in other words, buggy_logger is an alias to the 'status' object without specifically using the alias keyword? Is that correct? So, in ruby, you just say

b = a

and then any changes you make to b afterwards are also reflected in a. Or is this only true because we're talking about Strings, which are mutable in Ruby?

# example-4.rb

status = "peace"

buggy_logger = status

print "Status: "
print buggy_logger << "\n" # <- This insertion is the bug.

def launch_nukes?(status)
  unless status == 'peace'
    return true
  else
    return false
  end 
end

print "Nukes Launched: #{launch_nukes?(status)}\n"

# => Status: peace
# => Nukes Launched: true
+2  A: 

Yes, it is because strings are objects. Try

buggy_logger = status.dup

If you want a distinct object with the same initial value.

As for your question about alias I suspect you aren't correctly understanding how alias is used in ruby; it's used on methods, not objects, and isn't related to mutability.

Note also that the same semantics would have applied with any class; if status had been an array, a file, or anything else (provided it had mutable state suitable for use as a logger), you would have gotten analogous results.

One warning about dup though. If your object refers to other objects, the copy will also refer to the same objects. It's fine once you start thinking about it the right way, but tricky till then.

MarkusQ
Oh, that's so cool -- I didn't know there was a dup method. Thanks.
Ah, ok. So it's not just strings. Thanks again.