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: object cloning, ruby on rails, variable reference to object.
Trackback this post | Subscribe to the comments via RSS Feed