Câu hỏi phỏng vấn Ruby
Câu hỏi

Describe a closure in Ruby

Câu trả lời

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.

Types of Closures in Ruby

Ruby supports three main types of closures: blocks, procs, and lambdas.

  1. 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.

  2. 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.

  3. 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

Characteristics of Closures

  • Environment Retention: Closures in Ruby can access variables from their defining scope even after that scope has exited. This is because they carry their co...
middle

middle

Gợi ý câu hỏi phỏng vấn

junior

Which of the expressions listed below will result in "false"?

junior

What is the return value for ...

junior

What is duck typing and how does it pertain to Ruby?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào