ruby metaprogramming 01

本文详细解析了Ruby中元编程的概念,包括方法查找、接收者与方法名参数的应用,以及如何通过定义`method_missing`方法来调用不存在的方法。文章还介绍了Ruby的祖先链机制,解释了如何在不同层级的类之间调用方法,并讨论了`self`变量的重要性及其实现原理。此外,提供了实用的Ruby方法示例,如`send`、`send_public`、`define_method`等,帮助开发者更灵活地操作类和对象。

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,

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值