Code blocks, iterations, and process objects for Ruby

Source: Internet
Author: User
Tags in python

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

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.