Introduction to Ruby's program structure _ruby topics

Source: Internet
Author: User
Tags class definition constant require


Summary, ruby program consists of one or more Ruby source files, the source file consists of modules, the module has control structure, class objects, methods, and expressions and other elements, following this idea to sum up Ruby's program organization structure.



First, source files



1.1. File contains


Copy Code code as follows:

#file1. RB
Inc_path=$0.sub (/\/\w+\.rb/, "") #Get the directory of the current path
$:.insert ( -1,inc_path) #Add the current path to the load path array

Require "FILE2.RB"
Require "FILE2.RB" #require include files will only be imported once

Load "FILE3.RB"
Load "FILE3.RB" #Each load will import the file unconditionally again



#file2. RB
Print "FILE2.RB is included\n"


#file3. RB
Print "File3 is included\n"





1.2, the source file execution order





Copy Code code as follows:

#coding =utf-8
=begin
This is
Multiline Comment
=end

End{print "end1\n"}
End{print "end2\n"}
#END block execution order is opposite to the order of appearance

Print "text\n"

Begin{print "begin1\n"}
Begin{print "begin2\n"}
#BEGINblocks are executed in the same order as they appear
#BEGIN-text-end

The content after the beginning of #__END__ is ignored

__end__
Print "no_text\n"





1.3. source file Writing rules



Case sensitive
A newline character can only have whitespace, and will be ignored
Classes and modules and constant names begin with uppercase letters, and variables begin with lowercase letters or Unicode



Second, module


Copy Code code as follows:

#module1. RB
Inc_path=$0.sub (/\/\w+\.rb/, "") #Get the directory of the current path
$:.insert ( -1,inc_path) #Add the current path to the load path array

Require "MODULE2.RB"

Print mymod::var1, "\ n"
Mymod.out

Include Mymod #Import Mymod to the current namespace
Print VAR1


#module2. RB
Print "MODULE2.RB is included\n"

Module Mymod
Var1=99 # Variables within the module
Var1=100 #constant in the module

Print "Mymode is Included,var1 is", var1, "\ n"

Def mymod.out #Methods in the module must be added to the module name

Print "Mymod.out run\n"
End
End





III. Control Structure



Ruby's control structure is just as sequential, branching and looping as any other language, but it is quite flexible in its writing.



3.1. If the branch structure


Copy Code code as follows:

#if. RB
num=100
If (num>200) # can be used to conditionally invert
Print "num>200\n"
Elsif num>100
Print "num>100\n"
Else
Print "num<=100\n" # this sentence is executed
End

The print "num<=100\n" if num<=100 #if statement can be postscripted, and the IF statement itself is also an expression with a value
If num<=100 then print "num<100\n" #thenAvailable: Replace





3.2. Case of branch structure





Copy Code code as follows:

num=100

Str1=\
Case
When num>200 then "num>200"
When num>100 then "num>100"
Else "num<=100" #else don't use then
End

Print str1, "\ n"


Case num
When 201:print "num>200" #: Play the same role as then
Print when num>100
else print "num<=100"
End





3.3. Circulation structure





Copy Code code as follows:

Num=1

While Num<5 #Antonym until
Print num
Num+=1
End

print "\ n"

arr1=[1,2,3,4,5]

For I in arr1
Print I
End







Copy Code code as follows:

Num=1
Loop{#notes {must be on the same line as loop
Num+=1
Next If Num==3 #does not output 3
Redo If num==4 #Execute the previous statement of this line in the loop body again.
Break if Num>5 # is greater than 5 to exit the loop
Print num
}
#output 25

#while, until,for can also be used Next,redo,break





3.4. Supplementary control structure





Copy Code code as follows:

Print "0 is true!" #0 is also true
Print ' empty string is true! ' # ' is also true
#only nil in ruby is judged to be false





Iv. Definition of methods



The method in Ruby supports default parameters, variable parameters, but not keyword parameters, which can be simulated by passing in a hash table, and the last sentence of the method executes the result of its return value.



4.1. General methods


Copy Code code as follows:

def Non_para
Print "This is Non_para method\n"
End

def Many_para (PARA1,DEFAULT_PARA2=2,*DYNAMIC_PARA3)
Print "Para is", para1, "\ n"
Print "Default_para is", Default_para2, "\ n"
For I in DYNAMIC_PARA3
Print I, ","
End
End

Non_para ()
Many_para (1,3,5,7,9)





4.2, the scope of the method



Ruby determines the scope of the method based on the method name, which increases the readability of the program.





Copy Code code as follows:

#coding =utf-8

str1= "ABCDEFG"

Def Str1.len #object method
Puts Self.length
End

Str1.len

Class Person
Def Person.info #class method is static method
Puts "This is a perosn"

End
End

Person.info





4.3, block



The block associated with the method provides extensibility for the method. A part of the logic in a method can be abstracted into block independent, unlike subroutine calls, block is flexible, which means that I can only complete the backbone of the method, and there are some logic that can be extended as needed to invoke the method.


Copy Code code as follows:

def func para1
Localvalue= "Local Value"
Yield (PARA1)
End

Func {|para1|print "value of Para1 is", para1, "\ n"}

Func (MB) do |para1|
Print "Double value of Para1 is", para1*2, "\ n"
#print local_value local variable cannot be inherited
End
#yield The last statement execution result is the return value of the method.





4.5, Method Supplement
You can undef the definition of a method name



Alias method name method aliases can define different names for the method



The & method gets a reference to the method, which is invoked using a method reference. Call Way



V. Classes and objects



5.1, the general class definition is as follows


Copy Code code as follows:

Class Person
Def initialize (name,age) #properties are defined in initialize
@name =name
@age =age
End
Def name# attribute cannot be accessed directly, it must be accessed through the method interface
@name
End
Def age
@age
End
End

P1=person.new ("Justsong") # will call initialize with the same parameters

Print P1.name, "\ n", P1.age





5.2. The access rights of the methods in the class are by default Public,ruby have a similar permission declaration way as C + +.





Copy Code code as follows:

Class Person
Def initialize (name,age) #properties are defined in initialize
@name =name
@age =age
End
Def name# attribute cannot be accessed directly, it must be accessed through the method interface
@name
End
Private#protected,public
Def age
@age
End
End

P1=person.new ("Justsong") # will call initialize with the same parameters

Print P1.name, "\ n"
#print p1.age,private call will be disabled





5.3, because the attribute must be accessed through the method interface, so the writing program is a bit cumbersome, you can use the method for shorthand.


Copy Code code as follows:

Class Person
Attr_reader:name # has read-only access
Attr_writer:age # has write-only access
Attr_accessor:country # has read and write permissions
Def initialize (name,age,country)
@name =name
@age =age
@country =country
End
End

# Actually ruby automatically generated some methods

P1=person.new ("Justsong") # will call initialize with the same parameters


Print P1.name, "\ n"
Print P1.country, "\ n"
#print P1.age, you are prompted not to define the appropriate method





5.4. Ruby classes also have class variables (static variables) and class methods (static methods)





Copy Code code as follows:

Class Person
Attr_reader:name
@ @country = "a" #static variable
Def initialize (name)
@name =name
End
Def Person.output #static method

Print "Country is", @ @country, \ n
End
End

Person.output

P1=person.new ("Zhangsan")
P2=person.new ("Lisi")
Print P1.name, "\ n", P2.name





5.5. Inheritance of class


Copy Code code as follows:

Class Person
Attr_reader:name
Def initialize (name)
@name =name
End
End

Class Student < person
Attr_reader:grade
def initialize (Name,grade)
Super (name) #Use super to call the parent class with the same name method
@grade =grade
End
End

S1=student.new ("Justsong", 10)
Print S1.name, "\ n", S1.grade





5.6. Nested class



Class is defined directly in the class, or when the class is defined with:: The owning class of the specified class.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.