- Comprehensive Ruby Programming
- Jordan Hudgens
- 141字
- 2021-07-02 21:13:32
Return behavior
Secondly, lambdas and procs have different behaviors when it comes to returning values from methods. To see this, I'm going to create a method called my_method:
def my_method
x = lambda {return}
x.call
p "Text within the method"
end
my_method
If I run this method, it prints out "Text within the method":

Now, let's try exactly the same implementation with a proc:
def my_method
x = Proc.new {return}
x.call
p "Text within the method"
end
my_method
When you run it this time, it returns a value of nil.

What happened is that when the proc saw the return word, it exited out of the entire method and returned a nil value. However, in the case of the lambda, it processed the remaining part of the method.
So, these are the subtle and yet important differences between lambdas and procs.
推薦閱讀
- Scala Design Patterns
- 樂學Web編程:網站制作不神秘
- Dependency Injection in .NET Core 2.0
- Python編程完全入門教程
- Magento 1.8 Development Cookbook
- PhpStorm Cookbook
- Learning Python by Building Games
- TypeScript項目開發實戰
- The HTML and CSS Workshop
- Salesforce Reporting and Dashboards
- Microsoft Azure Storage Essentials
- 第一行代碼 C語言(視頻講解版)
- 現代C++編程實戰:132個核心技巧示例(原書第2版)
- Spring Boot實戰
- Learning Ionic