- 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.
- Data Visualization with D3 4.x Cookbook(Second Edition)
- PHP 從入門到項目實踐(超值版)
- OpenCV實例精解
- Clojure for Domain:specific Languages
- 深入理解Java7:核心技術與最佳實踐
- 名師講壇:Java微服務架構實戰(SpringBoot+SpringCloud+Docker+RabbitMQ)
- Mastering JBoss Enterprise Application Platform 7
- 自然語言處理Python進階
- 深入理解Android:Wi-Fi、NFC和GPS卷
- R數據科學實戰:工具詳解與案例分析
- Python語言科研繪圖與學術圖表繪制從入門到精通
- Django Design Patterns and Best Practices
- WildFly Cookbook
- 奔跑吧 Linux內核
- JavaScript Unit Testing