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) [/ruby] 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
I just like the valuable info you supply in your articles. I’ll bookmark your weblog and take a look at once more here regularly. I am relatively sure I will be told plenty of new stuff right right here! Good luck for the next!
Greetings! Very useful advice in this particular article! It’s the little changes that will make the largest changes. Thanks a lot for sharing!
Terrific article! That is the kind of info that should be shared around the net. Shame on Google for now not positioning this publish upper! Come on over and consult with my web site . Thanks =)