Introduction to ruby program structure and ruby program structure

Source: Internet
Author: User

Introduction to ruby program structure and ruby program structure

Generally, a ruby program is composed of one or more ruby source files. The source files are composed of modules. The module contains control structures, class objects, methods, expressions, and other elements, next we will summarize the ruby program organization structure based on this idea.

I. source files

1.1 File Inclusion
 Copy codeThe Code is as follows:
# File1.rb
Inc_path = $ 0.sub( // \/\ w + \. rb/, "") # obtain 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" # The require file is imported only once.

Load "file3.rb"
Load "file3.rb" # the file will be imported again unconditionally every time you load the file.


# File2.rb
Print "file2.rb is supported ded \ n"


# File3.rb
Print "file3 is supported ded \ n"
 

1.2 execution sequence of source files


Copy codeThe Code is as follows:
# Coding = UTF-8
= Begin
Here is
Multi-line comment
= End

END {print "end1 \ n "}
END {print "end2 \ n "}
# The execution sequence of the END block is the opposite to the display sequence.

Print "text \ n"

BEGIN {print "begin1 \ n "}
BEGIN {print "begin2 \ n "}
# The execution sequence of the BEGIN block is the same as that of the show Block
# BEGIN-TEXT-END

The content after the row starting with #__ END _ is ignored.
_ END __
Print "no_text \ n"

1.3 source file writing rules

◆ Case sensitive
◆ Line breaks can only be left blank and ignored
◆ Class, module, and constant names must start with an uppercase letter, and variables must start with lowercase letters or unicode

Ii. Modules
Copy codeThe Code is as follows:
# Module1.rb
Inc_path = $ 0.sub( // \/\ w + \. rb/, "") # obtain 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 supported ded \ n"

Module Mymod
Var1 = 99 # variables in the module
VAR1 = 100 # constants in the module

Print "Mymode is supported ded, var1 is", var1, "\ n"

Def Mymod. out # The Module name must be added to the method in the module.
Print "Mymod. out run \ n"
End
End

Iii. Control Structure

Like other languages, ruby's control structure is nothing more than sequence, branches, and loops, but it is quite flexible in writing.

3.1. if
Copy codeThe Code is as follows:
# If. rb
Num = 100
If (num> 200) # You can use unless to retrieve the inverse condition.
Print "num> 200 \ n"
Elsif num & gt; 100
Print "num> 100 \ n"
Else
Print "num <= 100 \ n" # execute this sentence
End

Print "num <= 100 \ n" if num <= 100 # The if statement can be followed, and the if statement itself also has a value
If num <= 100 then print "num <100 \ n" # then available: replace

3.2 branch structure case

Copy codeThe Code is as follows:
Num = 100

Str1 = \
Case
When num> 200 then "num> 200"
When num> 100 then "num> 100"
Else "num <= 100" # else does not use then
End

Print str1, "\ n"


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

3.3. Loop Structure

Copy codeThe Code is as follows:
Num = 1

While num <5 # antonym
Print num
Num + = 1
End

Print "\ n"

Arr1 = [1, 2, 4, 5]

For I in arr1
Print I
End

Copy codeThe Code is as follows:
Num = 1
Loop {# Note {must be in the same line as loop
Num + = 1
Next if num = 3 # No output 3
Redo if num = 4 # Run the previous statement in the loop body.
Break if num> 5 # exit the loop if it is greater than 5
Print num
}
# Output 25
# While, until, for can also be used next, redo, break

3.4 supplement to control structure

Copy codeThe Code is as follows:
Print "0 is true! "#0 is true
Print "empty string is true! "#" "Is also true
# In ruby, only nil is judged to be false.

Iv. method definition

Methods In ruby support default parameters, which are variable parameters but not keyword parameters. You can simulate the implementation by passing in a hash. The execution result of the last sentence of the method is the return value.

4.1 General Method
Copy codeThe Code is as follows:
Def non_para
Print "this is non_para method \ n"
End

Def many_para (para1, default_para2 = 2, * dynamic_para3)
Print "first 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 scope of action

Ruby determines the scope of a method based on the method name. This increases the readability of the program.

Copy codeThe Code is 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: Static Method
Puts "this is a perosn"
End
End

Person.info

4.3 BLOCK

The BLOCK associated with the method provides scalability for the method. A part of the logic in a method can be abstracted as a BLOCK independent. Different from a subroutine call, the BLOCK is flexible. That is to say, I can only complete the main part of the method, some logics can be extended when the method is called as needed.
Copy codeThe Code is as follows:
Def func para1
Localvalue = "local value"
Yield (para1)
End

Func (100) {| para1 | print "value of para1 is", para1, "\ n "}

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

4.5 Method supplement
◆ You can cancel the definition of a method by using the undef method name.

◆ Alias method name the method alias can define different names for the method

◆ & Method get method reference. The method reference. call method is used for calling.

V. Classes and objects

5.1. Common classes are defined as follows:
Copy codeThe Code is as follows:
Class Person
Def initialize (name, age) # attributes defined in initialize
@ Name = name
@ Age = age
End
Def name # The attribute cannot be directly accessed and must be accessed through the method interface.
@ Name
End
Def age
@ Age
End
End

P1 = Person. new ("justsong", 28) # initialize is called with the same Parameter
Print p1.name, "\ n", p1.age

5.2 The default access permission for methods in the class is public, and ruby has a permission declaration method similar to c ++.

Copy codeThe Code is as follows:
Class Person
Def initialize (name, age) # attributes defined in initialize
@ Name = name
@ Age = age
End
Def name # The attribute cannot be directly accessed and must be accessed through the method interface.
@ Name
End
Private # protected, public
Def age
@ Age
End
End

P1 = Person. new ("justsong", 28) # initialize is called with the same Parameter
Print p1.name, "\ n"
# Print p1.age, private call will be disabled

5.3 because attributes must be accessed through method interfaces, It is cumbersome to write programs. You can use the following method for short.
Copy codeThe Code is as follows:
Class Person
Attr_reader: name # Read-Only permission
Attr_writer: age # has the write-only permission.
Attr_accessor: country # has read and write permissions
Def initialize (name, age, country)
@ Name = name
@ Age = age
@ Country = country
End
End

# In fact, ruby automatically generates some methods

P1 = Person. new ("justsong", 28, "china") # initialize is called with the same Parameter

Print p1.name, "\ n"
Print p1.country, "\ n"
# Print p1.age, the system will prompt that the corresponding method is not defined

5.4 ruby classes also have class variables (static variables) and class methods (static methods)

Copy codeThe Code is as follows:
Class Person
Attr_reader: name
@ Country = "china" # static variables
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. class inheritance
Copy codeThe Code is 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 methods with the same name as the parent class
@ Grade = grade
End
End

S1 = Student. new ("justsong", 10)
Print s1.name, "\ n", s1.grade

5.6. Nested classes

Define a class directly in the class, or use: the class of the specified class when defining the 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.