Ruby variables

September 24, 2009

Something that you might have to watch out for when working with Ruby is how it works with variables. Ruby variables are only references (pointers) to objects. Therefore, you might experience a subtle behavior that you probably don’t expect. Try this out in your irb:

irb(main):001:0> a = "some text"
=> "some text"
irb(main):002:0> b = a
=> "some text"
irb(main):003:0> a.object_id
=> 23109650
irb(main):004:0> b.object_id
=> 23109650
irb(main):005:0> a.gsub!(/ text/, "thing different")
=> "something different"
irb(main):006:0> b
=> "something different"
irb(main):007:0>

First, we assign a String object “some text”. We could have written it fully as a = String.new(“some text”).

Second, we say b = a, and for Ruby this means that b will now point to the same object as a, and you can verify it by running object_id on both variables. But now comes the catch – if you modify a, b will be automatically modified. So, by running gsub! on a, we also modify b.

However, if you assign a new value to one of those linked variables, the link breaks down, as now one of the variables points to another object. So, if you type a = “some new text”, b will not change, and actually a and b will now point to 2 different objects.

If you want to create a copy of an object and point a variable to it, instead of b = a, you could have cloned the object: b = a.clone.

Entry Filed under: Uncategorized. Tags: , , .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent posts

Starting to learn Rails?

Archive

Recent comments

gogetakame on Installing Rails on Windows (3…
gogetakame on Installing Rails on Windows (3…
allaboutruby on Installing Rails on Windows (3…
Harsha on Installing Rails on Windows (3…
Eddy Josafat on Google Maps API in Rails (YM4R…