现在的位置: 首页 > 综合 > 正文

Ruby 元编程 类的真相

2018年09月08日 ⁄ 综合 ⁄ 共 2494字 ⁄ 字号 评论关闭

什么是对象:对象无非就是一组实例变量外加一个指向其类的引用。对象的方法并不存在与对象本身,而是存在与对象的类中。在类中,这些方法被称为类的实例方法

什么是类 : 类无非是一个对象(class 的实例)外加一组实例方法和一个指向其超类的引用。Class类是Module类的子类,因此一个类也是一个模块

跟任何其他对象一样,类有自己的方法如new(),这些是Class的实例方法,跟其他类一样,需要引用才能用访问

1.Array.each_with_index

beikong-eshare(demo): irb
2.0.0p247 :001 > a=['1','a','b','c']
 => ["1", "a", "b", "c"] 
2.0.0p247 :002 > a.each_with_index do |e,i|
2.0.0p247 :003 >     p e
2.0.0p247 :004?>     p i
2.0.0p247 :005?>     a[i] = 'java' if e == 'b'
2.0.0p247 :006?>   end
"1"
0
"a"
1
"b"
2
"c"
3
 => ["1", "a", "java", "c"] 

2.obj.instance_variables

2.0.0p247 :009 >   class MyClass 
2.0.0p247 :010?>   def my_method
2.0.0p247 :011?>     @v = 1
2.0.0p247 :012?>     end
2.0.0p247 :013?>   end

2.0.0p247 :017 > obj.instance_variables
 => [:@v] 
2.0.0p247 :018 > 

2.0.0p247 :019 > MyClass.instance_methods
 => [:my_method, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, :clone, :dup, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :to_s, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__] 
2.0.0p247 :020 > 

3.重访类

2.0.0p247 :022 >   String.superclass
 => Object 
2.0.0p247 :023 > Object.superclass
 => BasicObject 
2.0.0p247 :024 > BasicObject.superclass
 => nil 
2.0.0p247 :025 > 
2.0.0p247 :026 >   Class.superclass
 => Module 
2.0.0p247 :027 > Module.superclass
 => Object 
2.0.0p247 :028 > 

4.常量的路径

5.调用一个方法是发生了什么

1.找到这个方法,称为方法查找  (向右一步,再向上)

2.0.0p247 :064 > Kernel.private_instance_methods
 => [:initialize_copy, :initialize_dup, :initialize_clone, :sprintf, :format, :Integer, :Float, :String, :Array, :Hash, :warn, :raise, :fail, :global_variables, :__method__, :__callee__, :__dir__, :eval, :local_variables, :iterator?, :block_given?, :catch, :throw, :loop, :respond_to_missing?, :trace_var, :untrace_var, :at_exit, :syscall, :open, :printf, :print, :putc, :puts, :gets, :readline, :select, :readlines, :`, :p, :test, :srand, :rand, :trap, :exec, :fork, :exit!, :system, :spawn, :sleep, :exit, :abort, :load, :require, :require_relative, :autoload, :autoload?, :proc, :lambda, :binding, :caller, :caller_locations, :Rational, :Complex, :set_trace_func, :gem, :gem_original_require] 
2.0.0p247 :066 > Kernel.private_instance_methods.grep(/^pr/)
 => [:printf, :print, :proc] 
2.0.0p247 :067 > 

2.执行这个方法,Ruby需要一个self

一 如果调用方法的接受者不是你自己,则必须明确指明一个接受者

二 私有方法只能被隐含接受者调用

2.0.0p247 :067 > String.ancestors
 => [String, Comparable, Object, Kernel, BasicObject] 

抱歉!评论已关闭.