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

What happens if a block is passed two a...

Câu trả lời

When a block in Ruby is passed two arguments but is designed to accept only one, it will raise an ArgumentError indicating a mismatch in the number of expected arguments. This error occurs because the block's arity (the number of arguments it expects) does not match the number of arguments provided.

In Ruby, blocks are flexible in how they handle parameters. If a block expects fewer arguments than are passed to it, the extra arguments are simply ignored. However, if a block expects more arguments than are provided, Ruby raises an ArgumentError. This behavior ensures that the block has all the information it requires to execute without encountering undefined variables.

For example, consider the following Ruby code:

def example_method
  yield(5, 10)
end

example_method do |x|
  puts x
end

In this case, the block provided to example_method expects only one argument. When example_method yields two arguments (5 and 10), the block only uses the first argument (5), and the second argument (10) is ignored. This does not raise an error because the block can still function with the given arguments.

However, if the situation were reversed, such as in this example:

def example_method
  yield(5)
end

example_method do |x, y|
  puts x + y
end

This would raise an ArgumentError because the block expects two arguments, but only one is provided. The block cannot execute as intended because it lacks the necessary information (y), leading to an error.

...

senior

senior

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

senior

Is a block an object?

middle

What is the difference between Proc invocation and lambda invocation?

middle

Which operator must be defined in order to implement the Comparable module?

Bình luận

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

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