Document directory
- Ruby class
- Class inheritance
- Polymorphism
- Dynamic Language
- Encoding
Ruby class
The first letter is capitalized. The instance variable name starts with @, and the method name and parameter name start with a lowercase letter or.
class Person
def initialize(name)
@name = name
@motherland = "china"
end
def talk
puts "my name is " + @name
puts "my motherland is " + @motherland
end
end
Because the talk function has no parameters, parentheses can be omitted.
The getter and setter functions can be defined as (take @ motherland as an example ):
def motherland
return @motherland
end
def motherland = (m)
@motherland = m
end
It can also be abbreviated as attr_reader: motherland and attr_writer: Mother. to be simpler, you can write it as attr_accessor: motherland, which includes both getter and setter.
You can use this class as follows:
p = Person.new("meteor")
puts p.motherland
p.motherland = "england"
p.talk
Class inheritance
Use the <symbol to represent inheritance
class Student < Person
def talk
puts "students, name: " + @name;
super.talk;
end
end
Specify the method for calling the parent class with super.
The final parent class of all classes is the object class, and the object class defines the new, initialize... method.
Polymorphism
Ruby functions cannot be overloaded. All Ruby functions are virtual compared with C ++, as if they are in other languages except C ++.
Dynamic Language
Ruby is a dynamic language. It can be further defined after the class definition in Ruby. New methods can be added to the class definition, the original method can be modified, and new variables can be added, you can even delete methods.
class Student
undef talk
end
UNDEF can have methods, local variables, constants, and not UNDEF classes or instance variables.
In addition, remove_method removes the current method definition and undef_method removes the definition of all methods.
Remove_const can remove constants or classes.
Encoding
In Ruby, sometimes "! "Or "? "Attached to method name ,"! "This method is destructive and may change the input parameters ,"? "Indicates that this is a Boolean method, and only true or false is returned.
Parentheses are often omitted in ruby.
If a return statement exists in Ruby functions, it will be returned at return, and a value may be returned. If the last line is an expression, the value of the expression will be automatically returned even if no return is written.