Refer to Metaprogramming in Ruby
eval
String can execute as code by eval which is a method of module Kernel.
instance_eval module_eval and class_eval
They are special type of evals.
Objects can use instance_eval to create methods. For classes, methods are class methods. Remember that anonymous class will be created.
module_eval and class_eval operates on classes and modules. By another word, they can not call on pure objects.
class_variables_get and class_variables_get
We can get and set class variables out of class.
class_variables
Method class_variables gives us a list of class variables.
instance_variable_get and instance_variable_set
They give us the ability to get and set the instance variable of object out of class.
const_get and const_set
They give us the ability to get and set the const out of class. Using them, we can even create classes in run time.
Object.const_set("Ruby", Class.new)
class_name = Object.const_get("Ruby")
class_name.class_eval do
def hello
puts "hello world"
end
end
r = class_name.new
r.hello
本文介绍了Ruby中的元编程技术,包括eval及其变种如instance_eval、module_eval和class_eval的使用方法,以及如何通过class_variables_get、class_variables_set、instance_variable_get、instance_variable_set、const_get和const_set来操作类变量、实例变量和常量。
169

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



