Unbound Methods: These methods are not associated to any particular object.
Let’s say we have a User class.
We can create UnboundMethod using Module#instance_method or Method#unbind
and can call after binding to an object.
What is binding?
object contains the execution context in the code.
The execution context consists of variables, methods, the value of self and block.
This context can be later accessed using binding function.
Now try to access name from the instance of Person class.
We can access the name instance variable using eval.
This method takes the code as the first argument and binding as the second argument.
We use Method#bind to bind an object to UnboundMethod.
But the allocation from bind is quite expensive.
That is why Ruby 2.7 has addedUnboundMethod#bind_call to avoid the intermediate allocation.
Let’s say we have a Manager class which is inherited from User class.
To call UnboundMethod:
Before Ruby 2.7
Apart from object, we can also pass parameters to bind_call similar to call method.
Following are benchmark results:
As we can see that bind_call is a bit faster than bind.call.