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:
greeter = Proc.new { |name| puts "Hello, #{name}!" }
greeter.call("Alice")
Here, greeter
is a proc that takes a name and prints a greeting.
Lambdas: Lambdas in Ruby are a special type of proc. They are defined using the lambda
keyword or the stabby lambda syntax ->
. Lambdas are similar to procs but they enforce the arity of arguments more strictly (i.e., the number of arguments passed to a lambda must exactly match the number expected) and they handle the return
keyword differently. In a lambda, return
will exit from the lambda itself, not from the enclosing method. For example:
doubler = ->(x) { x * 2 }
puts doubler.call(5) # Outputs: 10
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào