Thursday 25 January 2007

ruby instance variables in derived classes

Note: The RichText blog has moved to www.ricroberts.com

I thought I would tell the world about something in the ruby language which surprised me a bit. Anyone who has used ruby for any length of time will no doubt already know this, but it took me off guard a little, coming from a C++, java and C# grounding in OO.

First a bit of background for the uninitiated... In ruby an instance variable is one preceded by an @ sign and, as with all variables in ruby, you can create one simply by assigning to it.

Anyway, in ruby, instance variables are automatically accessible to any derived classes. This is especially pertinent in rails, when dealing with the (base) ApplicationController. If you add a before_filter method to the ApplicationController, which assigns some instance variables, they are magically available in the derived controllers, without having to add accessor attributes to the base class.

Here is a very simple example...

class Parent
def parent_meth
@var = 'hello'
end
end

class Child < Parent
def child_meth
@var
end
end

>> child = Child.new
=> #
>> child.parent_meth
=> "hello"
>> child.child_meth
=> "hello"
As I said, I'm sure this is child's play for most rubyists, but I've read Dave Thomas's Ruby "Pick Axe" book, and don't remember seeing this explicitly said anywhere. In languages like C#, variables are private unless made otherwise (e.g. by use of an access modifier, or exposed by a property/method). It appears that in ruby, instance variables are by default protected. (Don't get me started on access modifiers - that's for another blog entry!).

I hope this post helps prevent some chin-scratching for other ruby newbies.

(If you're intersted in reading more about this topic, here's a discussion I started in the ruby forum).



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

No comments: