What Ruby sees when you monkeypatch

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com

Interesting:

That is, the code:

module Foo
puts Foo.object_id
end

is functionally equivalent to:

# Create a new Module instance and assign it to the Foo constant
Foo = Module.new

# Reopen the Module instance assigned to the constant Foo for modification
module Foo
# Do stuff in here to add functionality to the Foo module
# Since Foo is already defined, we can get its object_id.
puts Foo.object_id
end

This certainly doesn’t make sense coming from a compiled language standpoint (after all, how do you know what Cashier is if you haven’t finished its definition yet?), but Ruby’s interpreted nature means that it tends to treat things like module and class definitions a bit more loosely, which is what is permitting this behavior.

Source