SomeClass.include(SomeModule)
vs.
SomeClass.send :include, SomeMo开发者_JAVA百科dule
Is there any differences between them? Why is the second way preferred? (At least I've found it more frequently in other people's code).
They are almost identical.
The difference is that if SomeClass#include
is private, the latter will still be able to call it due to the nature of Object#send
If SomeClass#include
was private and you went with the former, it would raise an error.
So the advantage of using the latter is that you can include a module no matter what the visibility is. (Whether or not you actually believe accessing private methods is the "right" thing to do is another story. It certainly gives you tremendous power).
You can re-open an existing class:
class SomeClass
include SomeModule
end
精彩评论