Document directory
- Overload?
- Super
- Class variable (static variable)
- Class Method (static method)
- Singleton Method
- Access Control
Overload?
Ruby supports default parameters, but there is no method overload in ruby.
Ruby supports variable parameters. * is added before the parameter name to indicate variable parameters.
def sum(*num)
numSum = 0;
num.each{|i| numSum += i};
return numSum;
end
puts sum()
puts sum(3,6,9)
If the subclass overrides the method of the parent class, the parent class method is completely overwritten regardless of whether the parameters are the same.
Super
In the subclass method, you can directly use super to call the parent class method.
class Sub < Base
def talk
super
puts "sub"
end
end
The sub function talk first executes the talk function of the parent class and then runs its own puts statement.
Class variable (static variable)
If the global variables and instance variables (class members) are not initialized, the default value is nil. class variables (static member variables) must be initialized.
Class Method (static method)
Before defining a class method, add the class name and a point "."
class Person
def Person.StaticMethon
puts "this is a static function";
end
end
Singleton Method
In Ruby, you can define a method separately for an instance of a class. That is to say, P1 and P2 are all instances of the person class, but P2 can have more methods than P1.
class Person
end
p1 = Person.new
p2 = Person.new
def p2.foo
end
Access Control
Ruby also has access control permissions, which can support public, protected, and private. methods are all public by default, except for initialize (initialize is always private ).
class Person
def talk
end
protected:talk
end
The preceding statement defines the talk method as protected. You can also write access control in the class, indicating that all methods after this permission are used.
class Person
private
def talk
end
def foo
end
end
In the above writing, both talk and foo are defined as private.
The access control in ruby is dynamic and can be changed in different places of the program as needed.