Methods and code segments of basic Ruby knowledge

Source: Internet
Author: User

Methods and code segments of basic Ruby knowledge

The method in Ruby is a code block with a name. It is a parameterized code associated with one or more objects. The method name, receiver (object), parameter value, and the value of the last expression must be provided as the return value. Similar to the Ruby method, a code block has no name and is called only through an iterator or indirectly.
 
(1) Method
(1) definition method

The definition method is
Copy codeThe Code is as follows:
Def method name (parameter list)
Method body
End

The last expression is returned as the return value. If there is a value, the return value is returned; if there is no value, the return value is nil. Return can be omitted.
The method defined in the class is the instance method. The instance method can be used on the Instance Object of the class. If a method is defined on a specific object, this method is a single-key method and can only be used on this object.

Copy codeThe Code is as follows:
Class Test
Def instance_method_test (v)
Puts "# {v}: instance method"
End
End
 
T1 = Test. new
T2 = Test. new
T1.instance _ method_test ("t1 ")
T2.instance _ method_test ("t2 ")
 
Def t1.singleton _ method_test (v)
Puts "# {v}: singleton method"
End
 
T1.singleton _ method_test ("t1 ")
# T2.singleton _ method_test ("t2 ")

In ruby, the method generally starts with a lower-case letter. If there is more than one word, it is separated by an underscore (see this habit ). Interestingly, the method name can end with an equal sign, question mark, and exclamation point. It has different meanings: it ends with an equal sign (=) to indicate that this is a value assignment method (write attribute ); with question mark (?) The end is an assertion method, which can answer the value of the caller's question, such as determining the size and exclamation point (!) It indicates a variable method at the end, which may affect the object state. Be careful when using this method. These three symbols are very interesting, but they are not necessary.

(2) Cancellation Method

The undef method name can be used to cancel the method. For an inherited method, undef can cancel the inherited method in the subclass, but does not cancel the method in the parent class.

(3) method parameters

Add the equal sign and value to the parameter to set the default value for this parameter. If the parameter has a default value, you can specify a value or no value for this parameter when calling the method.
Copy codeThe Code is as follows:
Def createRole (name, level = 1)
Puts "role name is # {: name} level is # {level }"
End
 
CreateRole ("way ")
CreateRole ("clound", 5)

By adding a star number (*) to the front of the parameter, you can specify the number of variable parameters for the method (array parameter), and the specified number can be at most one.
Copy codeThe Code is as follows:
Def add_Person (* users)
Puts users
End
Add_Person ("a1", "a2 ")
Add_Person ("a1", "a2", "a3 ")

If you want to pass the array to the method, add the star number (*) before the array (*).

(2) code block
After a method is called, a code block can be followed. The method associated with the code block can be called through yield.
Copy codeThe Code is as follows:
Def showMessage (I)
Yield I * 2
Print I
End
 
ShowMessage (5) {| x | print "# {x }"}

The code block is called through yield or can be passed as a method parameter, provided that & is added as the prefix before this parameter and is the last parameter. At this time, it is passed as a proc object. It cannot be called through yield, but through the call method of proc. In addition, if the proc object is passed to the method in the display mode, the parameter defined by the method is not prefixed. With the & prefix, the code block can be associated with any method call, even if this method does not have a yield statement. The & parameter can be used as the last parameter for any method call. All methods supporting to_proc can be used &.
Copy codeThe Code is as follows:
# Pass the code block. The code block parameter must be the last one, and the & prefix is added. The call method of proc is used for calling.
Def fun_block (I, & B)
B. call (I * 2)
End
Fun_block (2) {| x | puts x}
 
# Display the passed proc object. The parameters of the proc object in the method are not prefixed
Def fun_proc (I, B)
B. call (I * 2)
End
P = Proc. new {| x | puts x}
Fun_proc (2, p)
 
C = [1, 2, 3, 4, 5, 6]
B = c. select {| x % 2 = 0}
P1 = Proc. new {| x % 2 = 0}
D = c. select (& p1)
Puts d

A code block is a syntax structure of Ruby. It is not an object, but an object can be created to represent a code block. Objects can be created in proc or lambda. The proc behavior is similar to the code block; the lambda behavior is similar to the method, but they are all instances of the Proc class.
 
Use Proc. new to create a proc. In version 1.9, it is synonymous with the proc method; Use the lambda Method to create a lambda. The lambda method does not contain parameters. The call period is associated with a code block.
 
In ruby 1.9, a new syntax is supported. Replace lambda with->, place the parameter outside curly brackets, and enclose it in parentheses. Only expressions are reserved in curly brackets. (Can be compared with lambda in. net3. *: () => {})
Copy codeThe Code is as follows:
# In 1.8k
D1 = lambda {| x + 1}
Puts d1.call (5)
# Replace lambda with-> in 1.9. The parameter is placed out of curly brackets and placed in parentheses. Only expressions are reserved in curly brackets.
# Similar to the lambda expression in. net3. * () => {}
D2 =-> (x) {x + 1}
D2.call (5)

This new syntax simplifies the code and unifies the code snippet with the ruby method, for example, setting the parameter default value.
(3) Closure

Both proc and lambda in ruby are closures ). A closure indicates that an object is both a callable function and a variable bound to this function. On the surface, the closure is: Method B in method A calls the variable of method A and returns the result. Method B is the closure. Its function: first, the variables of Method B can be used outside the method; second, the variables in method A can be used safely; and third, the values in Method B can be cached.
(For more information about closures, see relevant documents. I am just a rough introduction here .)

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.