Constant in Ruby

Assignment changes the reference for a particular variable.

  x = "foo"
  a = x
  x.gsub(/foo/, "bar")
  a # -> "bar"

  x = "foo"
  a = x
  x = "bar"
  a # -> "foo"

This is true whether you're dealing with variables or constants.

I think I'm might be missing something here.

In the examples above by just reading the code I would have originally
expected a to return "foo" in both examples (which it does for me
running it through irb).

But after thinking about it a little more, if you use gsub! the first
example does return a #=> "bar" (just a typo I think)

x = "foo"
a = x
x.gsub!(/foo/,"bar")
a #=> "bar"

Please correct me if I am off base here but what I think is happening is
that when we set a = x what we are really doing is creating a reference
a to the same object that x points to (which happens to be "foo"). Then
when we modify the object that x is referencing (changing foo to bar) a
also changes since it points to the same object.

In the second example when we do x = "bar" we are changing x to point to
a new object leaving a pointing to the original object "foo".

I will have to give this some more thought as it has some interesting
implications. I was originally expecting a to point to a _copy_ of what
x pointed to not the same object.

--Bill

I think I'm might be missing something here.

In the examples above by just reading the code I would have originally
expected a to return "foo" in both examples (which it does for me
running it through irb).

But after thinking about it a little more, if you use gsub! the first
example does return a #=> "bar" (just a typo I think)

Yes. That's a typo.

Please correct me if I am off base here but what I think is happening is
that when we set a = x what we are really doing is creating a reference
a to the same object that x points to (which happens to be "foo"). Then
when we modify the object that x is referencing (changing foo to bar) a
also changes since it points to the same object.

Yes, but that's overthinking it. Jim Weirich's "Shoeboxes and
Bindings" article[1] helps here.

Variables are labels. Constants are just special variables. Variables
in Ruby are different than they are in any other language I've used.
Variables in Ruby are pure references and do not represent any storage
space in and of themselves. Variables are simply "the name by which we
operate on an object". So when I do:

  x = "bar"
  a = x

I have said that the particular instance of string "bar" is able to be
referred to by the name x. And then I've said that the object referred
to by the name x can be referred to by the name a. So now we have one
object with two names.

If you want a copy, you have to either #dup or #clone the object.

The object is the atomic element here.

-austin
[1] http://onestepback.org/index.cgi/2003/12/15

···

On 5/5/06, William (Bill) Froelich <wfroelich@dbsnow.com> wrote:
--
Austin Ziegler * halostatue@gmail.com
               * Alternate: austin@halostatue.ca