官术网_书友最值得收藏!

What is a block?

So what exactly is a block? In other programming languages, a block is called a closure. Blocks allow you to group statements together and encapsulate behavior.

There are two ways to create blocks in Ruby and we'll use a proc to illustrate them:

  • Using curly braces

We'll begin by illustrating how to use blocks with the curly braces syntax, as shown here:

        add = Proc.new { |x, y| x + y} 
add[1, 2]

Running this code will return 3. The code inside of the curly braces is inside the block

  • Using do...end

The alternate way to use blocks is using the do...end syntax:

        add = Proc.new do |x, y| 
x + y
end

add[1, 2]

This will give you the same result as when we used the curly bracket syntax. A rule of thumb in Ruby is to use curly braces when you want to have all logic on the same line. Technically, you can write your program in a single line if you use curly braces.

The next obvious question is: why use procs when you can use methods to perform the same functionality? The answer is that procs give you more flexibility than methods. With procs you can store an entire set of processes inside a variable and then call the variable anywhere else in your program.

主站蜘蛛池模板: 南雄市| 延长县| 金门县| 阳谷县| 化德县| 景宁| 桐城市| 仁布县| 河南省| 锡林浩特市| 堆龙德庆县| 弥渡县| 方正县| 莲花县| 潼南县| 辛集市| 汉沽区| 汨罗市| 红原县| 马山县| 吉木乃县| 青田县| 鸡东县| 丽水市| 祁门县| 吴江市| 曲沃县| 嘉荫县| 尉犁县| 仁怀市| 上林县| 尚义县| 隆安县| 庄河市| 石阡县| 明溪县| 克东县| 华蓥市| 大关县| 平阳县| 密云县|