I got a sample code that turns a block into an object using Proc.new
so that it can be executed independently. There are two puts
at the end to print the result, in this example, the array is brought into the block for execution. At this point, I have something that I don't understand.
In the following code, why is .iterate!(square)
valid? They are the method defined in the class and the name of a separate block object. Why can they be written together?
Second, what is the working process of def iterate!(code)
? Why is the value being carried into (code)
? And what are self
and code.call
here?
square = Proc.new do |n|
n ** 2
end
class Array
def iterate!(code)
self.map {|n| code.call(n)}
end
end
puts [1, 2, 3].iterate!(square)
puts [4, 5, 6].iterate!(square)
I'm a beginner, please explain as detailed as possible, thank you.
CodePudding user response:
square = Proc.new do |n|
n ** 2
end
This is a simple proc, which expect an integer argument, and return square of the argument.
eg:
square.call(5) => 25
square.(5) => 25
Now, You have opened Array class and added iterate!
method which takes an argument. and the method just work on self (self here refers to same array on which you are calling the iterate method. here self = [1,2,3] in your first case and [4,5,6] in you second case.
in the iterate! method definition, you are mapping/looping the array elements and you are calling the square
proc with each element as arguments.
So it is more like
square.call(1) => 1
square.call(2) => 4
square.call(3) => 9