- Comprehensive Ruby Programming
- Jordan Hudgens
- 223字
- 2021-07-02 21:13:31
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.
- 計算機網絡
- Visual C++串口通信開發入門與編程實踐
- Pandas Cookbook
- Practical Data Science Cookbook(Second Edition)
- 網頁設計與制作教程(HTML+CSS+JavaScript)(第2版)
- Java Web開發技術教程
- Python機器學習編程與實戰
- C++面向對象程序設計習題解答與上機指導(第三版)
- Getting Started with Hazelcast(Second Edition)
- 零基礎Java學習筆記
- 西門子S7-200 SMART PLC編程從入門到實踐
- Test-Driven Machine Learning
- 移動增值應用開發技術導論
- Arduino機器人系統設計及開發
- Node.js 6.x Blueprints