How does block invocation differ from method invocation?
How does block invocation differ from method invocation?
In programming, particularly in languages like Ruby, the concepts of block invocation and method invocation represent two distinct ways of executing code, each with its own characteristics and uses.
A block in Ruby is a chunk of code that is passed to a method as an argument. Blocks are defined using either curly braces {}
or the do...end
syntax. They are not objects on their own but can be converted into objects of the Proc class. Blocks can capture variables from the context where they are defined (lexical scoping).
Blocks are typically used with methods like .each
, .map
, or .select
, which yield each element of a collection to the block. The method invokes the block by passing it arguments, if necessary, and the block performs operations on these arguments. Here's an example:
[1, 2, 3].each do |number|
puts number * 2
end
In this example, .each
is the method and the code within do...end
is the block. The block is invoked for each element of the array, and it executes the code within it, which in this case, prints each number multiplied by two[1].
Method invocation, on the other hand, involves calling a method of an object or a class. Methods are defined with a specific name and can be invoked anywhere within their visibility scope using the method name. They can accept arguments and return values. Methods are objects of the class Method
and can be reused multiple times.
Methods are invoked by specifying the object (unless they are class methods), the method name, and any arguments. For example:
class Calculator
def multiply(x, y)
x * y
end
end
calc = Calculator.new
puts calc.multiply(5, 3)
Here, multiply
is a method defined in the Calculator
class, and it is invoked on an instance of the class with two arguments, 5 and 3. The method performs a multiplication operation and returns the re...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào