Ruby Class Cheat sheet
Ruby September 25th, 2007The following is my ruby class cheat sheet, aimed at developers new to ruby and rails.
class MyClass #class declaration, notice the capital letter as this is a Constant
attr_reader :readOnlyProperty, … #shortcut to save writing a property getter
attr_writer :writeOnlyProperty, … #shortcut to save writing a property setter
attr_accessor :readWriteProperty, … #shortcut to save writing a property setter and getter
def initialize #class initialization method
@instanceVar=1 #instance variable, available throughout an instance of the class.
@readOnlyProperty=2
@writeOnlyProperty=3
@readWriteProperty=4
end
def instanceVar #property getter
@instanceVar #return the value of the instance variable
end
def instanceVar=(value) #property setter
@instanceVar = value # set the instance variable to the passed in value
end
def instanceMethod #instance method, available to all instances, this is the instance
end
def MyClass.classMethod #class method, only accessible via the class, this is the class
end
CLASSCONSTANT = ["a","b","c"] #constant defined by the class accessible by all instances note its in uppercase
end
I hope you have found this useful. If you have anything to add please comment.
Recent Comments