Everything in Ruby is an object. Even a block of code is an Object! In Ruby, a code object is called a block of code. You can imagine a code block as a small program unit. They contain Ruby code and can be transferred to the method when they are executed. A similar concept in python,c and Java is function pointers, anonymous functions, inner classes, and callback functions.
The syntax for Ruby code blocks is to place ruby code between curly braces or between do/end commands. As shown below:
{
#这是一个代码块...
}
do
#...并且这也是一个代码块
end
In a very simple instance, {puts "Hello World"} is a valid block of code. So how do you use these blocks of code and pass them as a set of code to a method? To do this, you first define a simple method such as the following:
def someMethod
yield
end
The command yield passes control to the code block (it is passed to this method). The following code shows you how a block of code is passed to this method.
irb(main):001:0> someMethod {puts "hello world"}
hello world
Executes the code block passed to the method whenever yield is invoked. Here is another example of a more complex method that uses a block of code to do more work.
irb(main):001:0>
def fibonacci (stop)
while stop < 20
stop=yield
end
end
=> nil
irb(main):006:0>
i=0; j=1; fibonacci(j) {puts i; temp = i; i = j;j = temp + j}
0
1
1
2
3
5
8