Describe a closure in Ruby
Describe a closure in Ruby
A closure in Ruby is a powerful and flexible programming construct that allows a block of code to be executed at a later time while retaining access to the scope in which it was created. This means that the closure can remember and use variables from its surrounding context even after those variables would normally go out of scope.
Ruby supports three main types of closures: blocks, procs, and lambdas.
Blocks: These are the simplest form of closures in Ruby. A block is a chunk of code enclosed either by curly braces {} or by do...end keywords. Blocks are passed to methods that yield to them, like iterators. For example:
[1, 2, 3].each { |n| puts n }
Here, the block { |n| puts n } is passed to the each method.
Procs: A proc is a block that has been encapsulated into an object of class Proc. This allows the block to be stored in a variable and passed around like any other object. Procs are more flexible than blocks because they can be called multiple times and passed into methods as objects. For example:
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.