[英]List of Ruby Metaprogramming methods?
剛開始學習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__]
是否有一個對元編程有用的方法列表? 例如instance_eval
, initialize
和method_missing
?
下面是從頂端回答這個頁面:
方法相關的鈎子
method_missing
method_added
singleton_method_added
method_removed
singleton_method_removed
method_undefined
singleton_method_undefined
類和模塊掛鈎
inherited
append_features
included
extend_object
extended
initialize_copy
const_missing
編組掛鈎
marshal_dump
marshal_load
強制鈎子
coerce
induced_from
to_xxx
另外,請查看此博客文章,了解其中許多方法的說明和示例代碼。
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
所有Method
,包括owner
東西。 Kernel#caller
有時很有用。 然后還查找ObjectSpace
類。
理解雖然它們有一些特殊的行為,但類和模塊只是對象,您可以動態創建它們,將它們存儲在數據結構中等等。它們甚至不必具有名稱。 你可以調用Class.new
來創建一個新的,並根據需要使用class_eval
, define_method
等來為它添加方法。
__LINE__
和__FILE__
可能很有趣,特別是File.read(__FILE__)
。
理解塊和lambdas對於一般的Ruby編程和特別是元編程都很重要。
在“Metaprogramming Ruby”一書中,作者指出元編程和編程之間沒有確定的界限。 這一切都只是編程。
我可以想到的一些例子是編程和元編程之間的class
和attr_reader
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.