The code block for Ruby Learning

Source: Internet
Author: User

Code blocks are more or less exposed in other languages, such as Perl sort{$a <=> $b}keys, the incoming code block is sorted by value, the closure is used in swift, further learning training closure, capturing The code style, such as value, has a deep understanding of the code block, and realizes that the code block is a reference type (Reference type), differs from the value type, and is aware of the similarities between blocks of code and classes, methods, and so on.

In the process of learning Ruby, the understanding of code blocks is a step further, not only simplifying the functionality of the code, but also involving scopes, callable objects and other knowledge.

code block

Code blocks are defined in curly braces or do...end keywords, and when a block is passed to a method, it can be recalled with the yield keyword while being able to pass the Kernel#block_given? () method detects whether a code block is passed in:

Class MyClass
? ? def My_method
? ? ? ? Return yield if Block_given?
? ? ? ? "There s no block"
? ? End
End
obj = MyClass.New
Puts obj.my_method{"There s a block!"}
Puts Obj.my_method

Blocks can also have their own parameters, in | | Separated by commas, the call can be invoked with yield (ARG):

def My_method
? ? return yield (2,3)
End
Puts My_method {|x,y| "The numbers is #{x} and #{y}"}

The above statement outputs the numbers is 2 and 3

Binding

Blocks can not only communicate with other statements by invoking parameters, but more importantly, when the block is defined, it gets the binding from the current scope:

def My_method
? ? return yield (2,3)
End
z = 4
Puts My_method {|x,y| "The There numbers is #{x},#{y} and #{z}"}

This is not difficult to understand: In a procedure statement, each statement can access other variables of the current scope, as well as the block, which takes the code that can be run as two parts: the code itself and a set of bindings.

If it's still a bit confusing, because the code block's {} does not imply a new scope, note that there is no {} in Ruby to start the end, but a python-like style.

Scope

So what really affects the scope in Ruby? In fact, only three keywords will open a new scope, called a "Scope gate":

Class, module, Def

Once you encounter one of these three keywords, it means entering a new scope and leaving when the End keyword appears, which you can understand as the scope door is the opening brace {, end can be seen as the closing brace}, if you want to understand that. There are subtle differences between class, module, and def: the Code in class and module definitions is executed immediately, and the code in the DEF definition is executed only when it is called.

Since scopes are only determined by these three keywords, there are several ways to traverse the scope gate, and let the code block get the binding of the upper scope: the Class.new (), Module.new, Module#define_method () method instead of class, module and DEF keywords:

var = "Top Level obj"
MyClass = Class.new Do
? ? Define_method:my_method do
? ? ? ? Puts Var
? ? End
End
obj = MyClass.New
Obj.my_method

As the code above, the Var can be accessed in My_method without being blocked by the scope gate, which becomes a flattened scope , with the flexibility to share scope and scope protection by leveraging the scope gate and traversing the scope gates.

Break Package

In the scope, there is also a black technology: Object#instance_eval () method. This method can pass a block, as a context probe , the receiver of the block that the method calls becomes self, at which point the block can access the recipient's private methods and instance variables, and even modify the self object without touching other bindings:

Class MyClass
? ? DEF Init
? ? ? ? @v = 1
? ? End
? ? Attr_reader:v
End

obj = MyClass.New
Obj.instance_eval {
? ? @v = 2
}
Puts OBJ.V

At this point, the V property of obj has been modified! So why call it black technology, because he can break the packaging structure, and it also has another role in the production of clean room .

Cleanroom is the class that is only designed to execute blocks of code:

Class Cleanroom
? ? def complex_calculation
? ? ? ? #...
? ? End
? ?
? ? def do_something
? ? ? ? #...
? ? End
End
Clean_room = Cleanroom.new
clean_room.instance_eval{
? ? If Complex_calculation > 10
? ? ? ? Do_something
? ? End
}?

The above is a clean room example

Callable Object

The use of blocks is divided into two steps: packaging and calling. There are three ways to easily call a block after it is packaged: proc, Lambda, and how to use it.

In Ruby, most things are objects, except for blocks, and if you want to package the blocks for storage, you need to call some classes to get help.

Proc is one of those classes. When you create a new proc class, the block that is called is stored and can then be called by call:

obj = proc.new{"This is a block"}
Puts Obj.call

In addition to Proc.new, Ruby provides two kernel methods for converting blocks into Proc:proc (), Lambda (), where Proc () Can be seen as an alias of Proc.new (after Ruby1.9), the difference is that lambda is more like a method, his return is returned from the lambda, and proc only represents the return from the current scope, as well as some of the others are not very clear differences.

Like in Swift, a block of code can be seen as the last hidden parameter of a method, or it can be named with the & sign (there is no connection here, but I remember it as if the block is a reference type, so the & symbol is used to pass in the reference):

def my_method (a,b,&operation)
? ? #...
End
My_method (+) {
? ? #...
}?

At this point, using & naming is also a way of storing blocks, which allows the contents of a block to be passed between multiple methods, or to pass the block to another proc.

The true meaning of the & symbol: Use a Proc object as a block, simply remove the &, and you can get the proc object again. Until that point, you can also use &proc to convert the proc back to a block elsewhere.

?

The code block for Ruby Learning

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.