# Must start with a capital letter, so Ruby silently creates the constant # to refer to the class. Capital letter is required.classMyClassdefhelloprint"Hello"endend>> myObj =MyClass.new>> myObj.hello
# Getter/Setter via metaprogramming# Metaprogramming allows to write, manipulate and# generate programs at runtime.classQuickClassattr_accessor :x, :y# attr_accessor defines a getter and setter end>> obj =QuickClass.new>> obj.x, obj.y =100,300# with attr_reader, a getter is definedclassQuickClassattr_reader :x, :ydefinitialize(x, y) @x, @y = x, yendend>> obj.x =123# !!!! Error# Attr # if used alone, it defines a getter, while # with 'True' it defines a setter too.classQuickClassattr :x,trueattr :ydefinitialize(x,y) @x, @y = x,yendend>> my_class =QuickClass.new(10,20)>> obj.x =100>> obj.y =200# error
# use self for declaring own class methods# these methods won't be visible per class instanceclassC1defself.sayprint"hello!"endend>>C1.say=>"hello!">> obj =C1.new>> obj.say =># !!!! error
Exercise:
classClassObj# class object @a constructor @a =100# Instance object getter/setter for @aattr_accessor :a# class object setter for @adefself.a=(val) @a = valend# class object getter for @a defself.a @a end# instance object @a constructordefinitialize(a) @a = a endend
Class methods may be defined in a few other ways
Using the class name instead of self keyword
Using the << notation: this is useful when you work with classes that have been already defined.
classOperationdefOperation.add(a,b) a + bendclass<<Operationdefmul(a,b) a * bendendend>>load classMethods.rb">> Operation.add 10,30 # => 30>> Operation.mul 10,20 # => 200
A class variable must start with special characters @@ and it is shared among all class instances: