Can someone give a clear example of instances where late and early binding occur in Ruby? Does ruby generally late-binds or early-binds?
If we refer to these terms as in this SO discussion, I'd rather say that Ruby tends to bind "late". Since Ruby is a dynamic language and code is evaluated at a run-time, there's no compiler that performs this job. Even if there's an error, no exception will be raised till the moment code is executed.
Does it already know where the function at run-time will reside in memory?
As you might already know everything in Ruby is an object, even classes and modules. An object itself is a bunch of instance variables and a link to a class i.e. another object. That way we have a chain all the way to BasicObject
which is the root object of Ruby and which doesn't have any ancestors.
Generally, the methods of an object reside in the object’s class. But the things go more complex in case of inheritance where some methods of parent classes can be also called on the object itself.
class A
def a_method
p "called from a_method"
end
end
class B < A
def b_method
p "called from b_method"
end
end
obj = B.new
obj.b_method # => called from b_method
obj.a_method # => called from a_method
So, the answer of this question is no but every time a method call on a particular object is done, Ruby performs the so called Method Look-up.
What happens when a function is called on an object in Ruby? What happens behind-the-scenes?
Method Look-up is a process where Ruby goes right into the class of the receiver and then up the ancestors chain, until it either finds the method or reaches the end of the chain. To illustrate this:
BasicObject
^
|
...
^
|
----------
| A |
----------
|a_method|
----------
^
|
----------
| B |
obj -------> ----------
|b_method|
----------
Hope I helped you :)