Ruby Study Notes-Method, Class

Source: Internet
Author: User

Method

A) Definition:

Def method name (parameter) # method parameters in ruby can be left blank

# Do something

End

Note: naming rules for method names: Start With lowercase letters or underscores (_), followed by numbers, letters, and underscores (_). Separate words with a hyphen:

Def hello_world

Puts "Hello world"

End

The method name can be followed by = ,?, !

"=": The parameter of this object is optional. If no parameter is specified during the call, the default

"?" : Indicates that this method is used to query functions.

"!" : Modify the method of receiving objects

 

B) method parameters:

1. Set the default value of a method parameter: when defining a method, you can specify the default value for some or all parameters. After adding an equal sign and a value to the parameter, you can specify a default value for the parameter, such:

Def hello (name = "ruby ")

Puts ("Hello, # {name }")

End

Hello ()

Hello ("world ")

In addition, the default value of a parameter may not be a constant, an arbitrary expression, a reference to an instance variable, or a reference to a previously defined parameter.

Def hello (a = 10, B = 5, c = a-B)

Puts a, B, c

End

Hello ()

Puts

Hello (1, 2, 10)

 

2. variable Length Parameter List: Ruby accepts any number of parameters. You need to add a * sign before a parameter. In the method code, this parameter is represented as an array, it contains 0 or multiple parameters passed to this location. For example:

Def hello (first, * rest)

P first

P rest

End

Hello ("11", "22", "33", "44", "55 ")

Note: In ruby1.9, the * hitting parameter should be placed behind the parameter with the default value, and then the common parameter can be specified, but the common parameter should be placed before the & hitting parameter.

 

3. hash table as a famous parameter: if a method has more than two or three parameters, it is difficult for the programmer to remember the order of parameters. In this case, we can use a hash object as a parameter, for example:

Def sequence (ARGs)

M = ARGs [: m]

C = ARGs [: C]

N = ARGs [: N]

A = []

3. Times {| I | A <m * I + c}

P a # => [10, 15, 20]

End

Sequence ({: N => 3,: M => 5,: c => 10}) # Call the method and pass the hash object

In addition, if the hash object is the last parameter (or there is only one block of code with the & header), Ruby allows omitting the braces of the hash literal.

Sequence (: N => 3,: M => 5,: c => 10)

Because method calls in Ruby can omit parentheses, they can also be written in the following form:

Sequence: N => 3,: M => 5,: c => 10

If parentheses are omitted, braces must be omitted. Otherwise, Ruby considers that you have passed a code block to this method.

 

4. code block parameters: In Ruby, each method call can keep up with a code block. Each method associated with a code block can call the code in the code block through the yield statement.

Def Hello (n, m, c)

I = 0

While (I <n)

Yield I * m + c

I + = 1

End

End

Hello (3,2, 1) {| x | puts x}

The code block is anonymous. If you want to explicitly control a code block, you can add a parameter at the end of the method and use & as the prefix of this parameter. This parameter points to the code block passed to the method. This parameter is a Proc object. It is called directly through the call method of Proc instead of using the yield statement:

Def sequence (n, m, c, & B)

I = 0

While (I <n)

B. call (I * m + c)

I + = 1

End

End

Sequence (5, 2, 2) {| x | puts x}

Or

Def sequence (n, m, c, B)

I = 0

While (I <n)

B. call (I * m + c)

I + = 1

End

End

P = Proc. new {| x | puts x}

Sequence (5, 2, 2, p )}

Note: The parameter of the block with the Ampersand and must be the last one to distinguish it from the array with the Ampersand omitted.

 

C) Return Value

The value of the last expression in the method code is returned as the value of the method call expression. In Ruby, you can use the return keyword to explicitly return the value of the expression. Of course, you can also use the return keyword to implicitly return the value of the expression.

 

Class

A) Definition

Class name

Def initialize (pram1, pram2 ,...)

@ Pram1 = pram1

@ Pram2 = pram2

...

End

...

End

 

Note: The first letter of the class name is capitalized, and the first letter of the subsequent words is also capitalized;

If the Initialize method is not defined, the system has an initialize method by default. You do not need to specify the parameter when instantiating a variable. If you customize the initialize method, objects are instantiated according to the format of the method;

In Ruby, you need to use the format "external class: Nested class. new" to instantiate the escape class.

 

B) Inheritance

Class SubCalss <SuperClass

...

End

 

C) accessors and attributes

Popular version:

Class Test

Def initialize (x, y)

@ X = x

@ Y = y

End

Def x; @ x; end

Def y; @ y; end

Def x = (value)

@ X = value

End

Def y = (value)

@ Y = value

End

End

 

Ultimate Edition:

Class Test

Attr_reader: X,: Y

# Attr_accessor

# Attr_writer

End

 

D) Class Method

In Ruby, a method that can be accessed directly by class name is called a class method. There are three methods to define a class method;

1) class name. Method Name

2) self. method name # (one of the purposes of using self is: dry, don't repeat yourself)

3) class <self

Def method name

...

End

...

End

 

E) class variables:

In Ruby, you can also define class variables. class variables must start with "@" and belong to a class. Therefore, when an instance of a class changes class variables, changes the class variables of the instance. That is, once the class variable changes, all the class variables called by the instance will change. Class variables must be initialized before use;

 

F) Access Control

PublicIt can be called by any instantiated object without restrictions on access control. The default method is public, except Initialize. The default method is private. The other exception is all "Global" methods defined outside the class. These methods are defined as private instance methods of the object.

ProtectedThis method class or its subclass object can only be defined. The entire family can be accessed.

PrivateObjects cannot be called directly, and the receiver can only be self. That is to say, private methods can only be called in the context of the current object.

 

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.