ruby metaprogramming 03

来源:互联网 发布:霍建华林心如形婚 知乎 编辑:程序博客网 时间:2024/06/06 06:52

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"  endendr = class_name.newr.hello

0 0
原创粉丝点击