WIP - Classes, Modules and Exceptions

Class Principles

Classes define what an object will look like.

# Must start with a capital letter, so Ruby silently creates the constant 
# to refer to the class. Capital letter is required.
class MyClass 
    def hello
        print "Hello"
    end
end

>> myObj = MyClass.new
>> myObj.hello

Exercise:

class ClassObj
  # class object @a constructor
  @a = 100
  
  # Instance object getter/setter for @a
  attr_accessor :a
 
  # class object setter for @a
  def self.a=(val)
   @a = val
  end
  
  # class object getter for @a  
  def self.a 
   @a 
  end
  
  # instance object @a constructor
  def initialize(a)
   @a = a 
  end
end

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.

class Operation
 
 def Operation.add(a,b)
   a + b
 end
 
 class << Operation
   def mul(a,b)
     a * b
   end
 end
end

>> 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:

Method Visibility

Subclassing and Inheritance

Modules

Exceptions

Conclusion

Last updated