Ruby 元编程 类定义

来源:互联网 发布:js 点击复制当前内容 编辑:程序博客网 时间:2024/04/30 06:45



1.类实例变量 

   

[ruby] view plaincopy
  1. 2.0.0p247 :342 >   class MyClass  
  2. 2.0.0p247 :343?>     @my_var = 1  
  3. 2.0.0p247 :344?>     def self.read  
  4. 2.0.0p247 :345?>       @my_var  
  5. 2.0.0p247 :346?>     end  
  6. 2.0.0p247 :347?>       
  7. 2.0.0p247 :348 >     def write; @my_var = 2; end  
  8. 2.0.0p247 :349?>     def read; @my_var;end  
  9. 2.0.0p247 :351?>   end  

类变量 

   class C

@@v = 1

end


2.单件方法

[ruby] view plaincopy
  1. 2.0.0p247 :319 > str = "any string paragraph"  
  2.  => "any string paragraph"   
  3. 2.0.0p247 :320 > def str.title?  
  4. 2.0.0p247 :321?>   self.upcase == self  
  5. 2.0.0p247 :322?>   end  
  6.  => nil   
  7. 2.0.0p247 :323 > str  
  8.  => "any string paragraph"   
  9. 2.0.0p247 :324 > str.title?  
  10.  => false   
  11. 2.0.0p247 :325 >   


3.类方法 和 单件方法其实是一样的


4.类宏

[ruby] view plaincopy
  1. 2.0.0p247 :362 > class MyClass  
  2. 2.0.0p247 :363?>     attr_accessor :my_atttribute  
  3. 2.0.0p247 :364?>   end  


5.eigenclass 单件类

[ruby] view plaincopy
  1. 2.0.0p247 :380 > class Object  
  2. 2.0.0p247 :381?>   def  
  3. 2.0.0p247 :382 >       eigenclass  
  4. 2.0.0p247 :383?>     class < selfselfend  
  5. 2.0.0p247 :384?>   end  
  6. SyntaxError: (irb):383: syntax error, unexpected '<'  
  7. class < selfselfend  
  8.        ^  
  9.     from /Users/menxu/.rvm/rubies/ruby-2.0.0-p247/bin/irb:16:in `<main>'  
  10. 2.0.0p247 :385 > class Object  
  11. 2.0.0p247 :386?>   def eigenclass  
  12. 2.0.0p247 :387?>     class << self;self ; end  
  13. 2.0.0p247 :388?>     end  
  14. 2.0.0p247 :389?>   end  
  15.  => nil   
  16. 2.0.0p247 :390 > "abc".eigenclass  
  17.  => #<Class:#<String:0x007fdaea9fdb30>>   
  18. 2.0.0p247 :391 > obj = Object.new  
  19.  => #<Object:0x007fdaea9eee78>   
  20. 2.0.0p247 :392 > class << obj  
  21. 2.0.0p247 :393?>   def a_singleton_method  
  22. 2.0.0p247 :394?>     "obj#a_singleton_method()"  
  23. 2.0.0p247 :395?>     end  
  24. 2.0.0p247 :396?>   end  
  25.  => nil   
  26. 2.0.0p247 :397 > obj.eigenclass  
  27.  => #<Class:#<Object:0x007fdaea9eee78>>   
  28. 2.0.0p247 :398 > obj.eigenclass.superclass  
  29.  => Object   
  30. 2.0.0p247 :399 > obj.a_singleton_method  
  31.  => "obj#a_singleton_method()"   
  32. 2.0.0p247 :400 >   

6.方法别名 alias
[ruby] view plaincopy
  1. 2.0.0p247 :412 >  ob = MyAlias.new  
  2.  => #<MyAlias:0x007fdaea94e950>   
  3. 2.0.0p247 :413 > ob.my_method  
  4.  => "my_method()"   
  5. 2.0.0p247 :414 > ob.m  
  6.  => "my_method()"   
  7. 2.0.0p247 :415 >   
  8. 2.0.0p247 :416 >    
0 0