Resource: Metaprogramming in Ruby
Methods look up
receiver.method_name args
Code above demonstrated how to call a method.
Receiver is optional and if you do not specified a receiver the receiver is set to
self that is decide by where your method call is.
If receiver do not have method named "method_name" exists then "method_missing" will be called. If we redefine method "method_missing" we can call anything not exist in your class.
When we call a method, ruby will go to the class of the receiver and try to find that method. It may not find it. But remember that Ruby class inherits other classes and we can call the methods inherited from superclass. When ruby can not find what it want it will go up to the superclass and have a try. Ruby recursively do that following the
ancestors chain. until it find that method or find the superclass is nil and then call method_missing.
Ancestors chain include not only classes but also module. When there is a module in the ancestors chain, a hidden class will be created to hold all the the methods and constants of that module. The following example is the ancestors chain of Fixnum 1.
irb>1.class.ancestors
[Fixnum, Integer, Numeric, Comparable, Object, Kernel, BasicObject]
In the ancestors array, Kernel and Coomparable are module.
self
Your programs runs in an object called
self all the time. The object also called
current object and it is always changing. But
self is a very special variable and it always references to the
current object.
Don't forget that : everything in ruby is object.
Some useful methods
1. send
You can call
all(public/private/protected) methods out of any class.
2.send_public
Call only public methods out of class.
3.define_method
You can write code to define methods for your classes
4.method_missing
This is a method called once the method you called is not exists in receiver. And if you redefine it then you can call any methods not exists.
5.remove_method
This method will remove a method in a class but will not remove the same method in the inheritance chain.
6.undef_method
This one will prevents a class to respond to a method even there are same method in the ancestors. It looks like the methods disappeared in the class and the objects created before we call undef_method will not responds to the method,
本文详细解析了Ruby中元编程的概念,包括方法查找、接收者与方法名参数的应用,以及如何通过定义`method_missing`方法来调用不存在的方法。文章还介绍了Ruby的祖先链机制,解释了如何在不同层级的类之间调用方法,并讨论了`self`变量的重要性及其实现原理。此外,提供了实用的Ruby方法示例,如`send`、`send_public`、`define_method`等,帮助开发者更灵活地操作类和对象。
169

被折叠的 条评论
为什么被折叠?



