Ruby 动态方法调用与系统特性全解析
1. 动态方法调用
在 Ruby 里,动态调用方法是一项强大的特性。Module.constants 会返回模块可用的所有常量,包含其超类的常量,若不需要超类常量,可从列表中减去。自 Ruby 1.8 起,反射方法默认会递归到父类及其祖先类,传入 false 可阻止这种递归。
在 C 和 Java 中,程序员常编写调度表来根据命令调用函数,例如下面的 C 代码:
typedef struct {
char *name;
void (*fptr)();
} Tuple;
Tuple list[] = {
{ "play", fptr_play },
{ "stop", fptr_stop },
{ "record", fptr_record },
{ 0, 0 },
};
void dispatch(char *cmd) {
int i = 0;
for (; list[i].name; i++) {
if (strncmp(list[i].name, cmd, strlen(cmd)) == 0) {
list[i].fptr();
return;
}
}
/* not found */
}
而在 Ruby 中,只需将命令函数放入一个类,创建该类的实例,然后使用 send
方法即可: