Ruby is an object-oriented programming language, which means the programming structure it operates on is called "object"
First go to the Code to understand the definition and usage of the class.
Class computer $ manufacturer = "Mango computer, Inc." @ files = {Hello: "Hello, world! "} Def initialize (username, password) @ username = username @ Password = PASSWORD end def CURRENT_USER @ username end def self. display_files @ files endend # Make a new computer instance: Hal = computer. new ("Dave", 12345) puts "current user: # {Hal. CURRENT_USER} "# @ username belongs to the Hal instance. puts "manufacturer :#{$ manufacturer}" # $ manufacturer is global! We can get it directly. puts "files: # {computer. display_files} "# @ files belongs to the computer class. --------------------------------------------------------------------- output: Current User: davemanufacturer: mango computer, Inc. files: {: Hello => "Hello, world! "} Nil
Class Definition
class Computer #class magic here end
According to the ruby naming convention, the first letter of the class name must be capitalized, and then the first letter of each word is capitalized. The two words are no longer separated by underscores (_).
class Computer def initialize endend
Observe the definition of the class above. The initialize method appears in the class. This method is used to initialize the class object. If this method is not used, the object cannot generate the object. (Constructor corresponding to C ++/Java)
class Computer $manufacturer = "Mango Computer, Inc." @@files = {hello: "Hello, world!"} def initialize(username, password) @username = username @password = password endend
In the ruby world, we add @ before a variable name to indicate that this variable is an instance variable, which means that this variable can only be accessed by instances of the class.
Local variables only apply to a specific method.
There are two @ before the variable name, that is, the @ variable, which is called a class variable. It does not belong to the class instance, but belongs to the class itself (similar to the static variable in C ++ ).
Global variables can be defined in two ways. One is defined out of all classes and methods. If you want to put global variables into the class, you can use another definition method by adding $ between variable names.
Create and use Ruby classes