B S*_*ven 7 ruby reflection methods metaprogramming object
刚开始学习Ruby元编程.看看Object.methods我得到:
Object.methods => [
:allocate,
:new,
:superclass,
:freeze,
:===,
:==,
:<=>,
:<,
:<=,
:>,
:>=,
:to_s,
:included_modules,
:include?,
:name,
:ancestors,
:instance_methods,
:public_instance_methods,
:protected_instance_methods,
:private_instance_methods,
:constants,
:const_get,
:const_set,
:const_defined?,
:const_missing,
:class_variables,
:remove_class_variable,
:class_variable_get,
:class_variable_set,
:class_variable_defined?,
:module_exec,
:class_exec,
:module_eval,
:class_eval,
:method_defined?,
:public_method_defined?,
:private_method_defined?,
:protected_method_defined?,
:public_class_method,
:private_class_method,
:autoload,
:autoload?,
:instance_method,
:public_instance_method,
:nil?,
:=~,
:!~,
:eql?,
:hash,
:class,
:singleton_class,
:clone,
:dup,
:initialize_dup,
:initialize_clone,
:taint,
:tainted?,
:untaint,
:untrust,
:untrusted?,
:trust,
:frozen?,
:inspect,
:methods,
:singleton_methods,
:protected_methods,
:private_methods,
:public_methods,
:instance_variables,
:instance_variable_get,
:instance_variable_set,
:instance_variable_defined?,
:instance_of?,
:kind_of?,
:is_a?,
:tap,
:send,
:public_send,
:respond_to?,
:respond_to_missing?,
:extend,
:display,
:method,
:public_method,
:define_singleton_method,
:__id__,
:object_id,
:to_enum,
:enum_for,
:equal?,
:!,
:!=,
:instance_eval,
:instance_exec,
:__send__]
Run Code Online (Sandbox Code Playgroud)
是否有一个对元编程有用的方法列表?如instance_eval,initialize和method_missing?
下面是从顶端回答这个页面:
方法相关的钩子
method_missing
method_added
singleton_method_added
method_removed
singleton_method_removed
method_undefined
singleton_method_undefined
Run Code Online (Sandbox Code Playgroud)
类和模块挂钩
inherited
append_features
included
extend_object
extended
initialize_copy
const_missing
Run Code Online (Sandbox Code Playgroud)
编组挂钩
marshal_dump
marshal_load
Run Code Online (Sandbox Code Playgroud)
强制钩子
coerce
induced_from
to_xxx
Run Code Online (Sandbox Code Playgroud)
另外,请查看此博客文章,了解其中许多方法的说明和示例代码.
Object是一个类,因此您列出的大多数方法实际上是Class实例方法.看看Object.private_methods- 你会发现define_method,这是绝对必要的.但是它binding也非常强大......在学习Ruby元编程时,你会想要查看Binding该类的文档.的send,__send__和public_send家人也是必不可少的.
查看上面的列表,您应该能够识别"反射"方法,这些方法可用于以编程方式查询和操作常量,方法,实例变量等.然后是eval和exec方法.method_missing是你学习的第一个,但const_missing也要注意.一定要检查set_trace_func和trace_var.而且我们会在哪里不alias和alias_method?
再就是翻译的"钩子"状method_added,method_removed,method_undefined,inherited,extended,included,singleton_method_added,singleton_method_removed,singleton_method_undefined,instance_method_added,instance_method_removed,和instance_method_undefined.
Object#method获取Method物品至关重要.看看所有的方法Method,包括像owner.Kernel#caller有时可能很有用.然后还要查看ObjectSpace课程.
理解虽然它们有一些特殊的行为,但类和模块只是对象,您可以动态创建它们,将它们存储在数据结构中等等.它们甚至不必具有名称.您只需拨打Class.new,使一个新的和使用class_eval,define_method根据需要方法添加到它,等等.
__LINE__并且__FILE__可能很有趣,尤其如此File.read(__FILE__).
理解块和lambdas对于一般的Ruby编程和特别是元编程都很重要.