Ruby Classes
Classes Classes in Ruby are similar to classes in other familiar languages with some interesting differences We will see how to write classes and different related features
Remember convention @ - instance variable @@ - class variable No symbol in front of it – local variable We will discuss this more soon
Initializing Initialize is a special method always private
Access Control private, public, protected like other languages Except private is really private only accessible on self, not even on other objects of same class You can’t call private explicitly using a receiver, it can only be called on an implicitly receiver There are some tricky ways to get around this… Default is public You can specify access control one of two ways
Especially useful when you Access Control… Especially useful when you want to make some attributes protected
Attributes – readers :name returns a Symbol object : represents name of a variable while variable name represents the value of the variable Creates year method and @year instance variable
Attributes - Writer OR
What’s wrong with this code? We’re missing an @ Coming from other languages we tend to do this for a while
A little gotcha The return value from assignment method is ignored
Inheritance You use < to express inheritance Super call’s respective base method
Inheritance… Ruby supports Single Inheritance like Java/C# But how about multiple inheritance No and Yes Not supported, but There is a very powerful Mixin – more about this later
Classes never closed You can add methods to any class you like
method_missing You can dynamically figure out what to do when methods are called Ruby calls method_missing when it can’t hande a method After adding method_missing