Ruby 元编程 类定义


1.类实例变量 

   

2.0.0p247 :342 >   class MyClass
2.0.0p247 :343?>     @my_var = 1
2.0.0p247 :344?>     def self.read
2.0.0p247 :345?>       @my_var
2.0.0p247 :346?>     end
2.0.0p247 :347?>     
2.0.0p247 :348 >     def write; @my_var = 2; end
2.0.0p247 :349?>     def read; @my_var;end
2.0.0p247 :351?>   end

类变量 

   class C

@@v = 1

end


2.单件方法

2.0.0p247 :319 > str = "any string paragraph"
 => "any string paragraph" 
2.0.0p247 :320 > def str.title?
2.0.0p247 :321?>   self.upcase == self
2.0.0p247 :322?>   end
 => nil 
2.0.0p247 :323 > str
 => "any string paragraph" 
2.0.0p247 :324 > str.title?
 => false 
2.0.0p247 :325 > 


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


4.类宏

2.0.0p247 :362 > class MyClass
2.0.0p247 :363?>     attr_accessor :my_atttribute
2.0.0p247 :364?>   end


5.eigenclass 单件类

2.0.0p247 :380 > class Object
2.0.0p247 :381?>   def
2.0.0p247 :382 >       eigenclass
2.0.0p247 :383?>     class < self; self; end
2.0.0p247 :384?>   end
SyntaxError: (irb):383: syntax error, unexpected '<'
class < self; self; end
       ^
	from /Users/menxu/.rvm/rubies/ruby-2.0.0-p247/bin/irb:16:in `<main>'
2.0.0p247 :385 > class Object
2.0.0p247 :386?>   def eigenclass
2.0.0p247 :387?>     class << self;self ; end
2.0.0p247 :388?>     end
2.0.0p247 :389?>   end
 => nil 
2.0.0p247 :390 > "abc".eigenclass
 => #<Class:#<String:0x007fdaea9fdb30>> 
2.0.0p247 :391 > obj = Object.new
 => #<Object:0x007fdaea9eee78> 
2.0.0p247 :392 > class << obj
2.0.0p247 :393?>   def a_singleton_method
2.0.0p247 :394?>     "obj#a_singleton_method()"
2.0.0p247 :395?>     end
2.0.0p247 :396?>   end
 => nil 
2.0.0p247 :397 > obj.eigenclass
 => #<Class:#<Object:0x007fdaea9eee78>> 
2.0.0p247 :398 > obj.eigenclass.superclass
 => Object 
2.0.0p247 :399 > obj.a_singleton_method
 => "obj#a_singleton_method()" 
2.0.0p247 :400 > 

6.方法别名 alias

2.0.0p247 :412 >  ob = MyAlias.new
 => #<MyAlias:0x007fdaea94e950> 
2.0.0p247 :413 > ob.my_method
 => "my_method()" 
2.0.0p247 :414 > ob.m
 => "my_method()" 
2.0.0p247 :415 > 
2.0.0p247 :416 >   

7.环绕别名  在新方法中调用l老方法


你可能感兴趣的:(Ruby,元编程,类定义)