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

What is the difference between Proc invocation and lambda invocation?

Câu trả lời

In Ruby, both procs and lambdas are objects of the class Proc, which are essentially blocks of code that have been bound to a set of local variables. However, there are key differences in their behavior, particularly when it comes to how they handle arguments and return statements.

Argument Handling

When invoking a proc, it doesn't enforce the number of arguments passed to it. If you pass too few arguments to a proc, the missing ones are set to nil. If you pass too many, the extra ones are ignored. This behavior can lead to subtle bugs if not handled carefully.

Lambdas, on the other hand, are more strict about the number of arguments. If you pass the wrong number of arguments to a lambda, it will raise an ArgumentError. This strictness can be helpful as it enforces the contract that the lambda expects, making the code more robust.

Return Behavior

Another significant difference is how procs and lambdas handle the return keyword. When you return from within a lambda, the control jumps back to the calling method after the lambda finishes executing. It's similar to how methods return control to their caller.

With procs, the return keyword will return from the method enclosing the proc. If the proc is not inside a method, calling return will throw an error. This means that a return within a proc can exit an enclosing method and prevent the subsequent code from running.

Example Usage

Here's an example to illustrate the differences:

def proc_and_lambda
  test_proc = Proc.new { return "Proc returned" }
...
middle

middle

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

middle

Why can you safely use a string as a hash key, even though a string is mutable?

junior

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

senior

Is a method an object?

Bình luận

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

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