Ruby variables

September 24, 2009 at 9:17 pm Leave a comment

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.

Advertisements

Entry filed under: Uncategorized. Tags: , , .

Timing attack? What’s that about? Rails caching – resources

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent posts

Starting to learn Rails?

Kindle

Get Kindle - the best e-book reader, that I personally use, and the only one that you can read on the beach - very useful: Kindle Wireless Reading Device (6" Display, Global Wireless, Latest Generation)

%d bloggers like this: