Download presentation
Presentation is loading. Please wait.
1
Ruby Classes
2
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
3
Remember convention @ - instance variable @@ - class variable
No symbol in front of it – local variable We will discuss this more soon
4
Initializing Initialize is a special method always private
5
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
6
Especially useful when you
Access Control… Especially useful when you want to make some attributes protected
7
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
8
Attributes - Writer OR
9
What’s wrong with this code?
We’re missing Coming from other languages we tend to do this for a while
10
A little gotcha The return value from assignment method is ignored
11
Inheritance You use < to express inheritance
Super call’s respective base method
12
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
13
Classes never closed You can add methods to any class you like
14
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.