Ruby Class

Class Definition

class Homuhomu
   def initialize(a)
      @a = a
   end
   def method1
      @a
   end
end
homuhomu = Homuhomu.new(1)
madoka = Homuhomu.new(2)
p homuhomu.method1
p madoka.method1

class

class classname
end

Create classname instance in the meaning of interpreter.

initialize

initialize is initial method(like constructor).

class

homuhomu.class == Homuhomu #=> true

class returns class name.

Extend class

class Madoka < Homuhomu
   def initialize(a, b)
      @b = b
      super a       # Run super class initialize
   end
   def method2(c)
      @a + @b + c
   end
end
 
madoka = Madoka.new(3,4)
p madoka.method1
p madoka.method2(5)
&#91;/ruby&#93;

Use <span style="color: #ff0000;"><strong>super</strong></span> for super class method
Constructor of super class can be located anywhere.(Not like java)

<h3>How to get super class</h3>
Use superclass method
[ruby]
Madoka.superclass == Homuhomu   #=> true

Methods

public, protected, private concept is same as Java

class Baz1
   def public_medhod1; 1; end   # Default is public
   public
      def public_method2; 2; end
   protected
      def protected_medhod1; 1; end
      def protected_method2; 2; end # protected
   private
      def private_method1; 1; end
end
 
Baz1.new.public_method1     #1
Baz1.new.public_method2     #2
Baz1.new.protected_medhod1  # NoMethodError
Baz1.new.protected_medhod1  # NoMethodError
Baz1.new.protected_medhod1  # NoMethodError

Use symbol

class Baz1
   def public_method1; 1; end
   def public_method2; 2; end
   def protected_method1; 1; end
   def protected_method2; 2; end
   def private_method1; 1; end
 
   public :pulic_method1, :public_method2   # public
   protected :protected_method1, :protected_method2  # protected
   private :private_method1
end

private

Cannot call using self

class Baz2
   def public_medthod1
      private_method1   # O.K.
   end
   def public_method2
      self.private_method1  # NG
   end
   private
   def private_method1; end
end

Change visibility

class Baz2Ext < Baz2
   public :private_method1
end
Baz2.new.private_method1    #=> NoMethodError
Baz2Ext.new.private_method1 #=> nil

Change super class visibility in sub class.

Accessor

class Homuhomu
   def name
      @name
   end

   def name=(name)
      @name = name
   end
end
class Homuhomu
   attr_reader :name
   attr_writer :name
end
class Homuhomu
   attr_accessor :name
end

Init

class Homuhomu
   attr_accessor :name

   def initialize
       @name ||= "Homuhomu"
   end
end

In case of boolean

def activated?
   @activated = true if @activated.nil?
end