Ruby元编程小结

2019-09-25 09:47:01王旭

  definitialize 
    @geek="Matz" 
  end 
end 
obj = Rubyist.new 
 
# instance_eval可以操纵obj的私有方法以及实例变量 
  
obj.instance_evaldo 
  putsself# => #puts@geek# => Matz 
end 
 
 
 通过instance_eval传递的代码块使得你可以在对象内部操作。你可以在对象内部肆意操纵,不再会有任何数据是私有的!instance_eval亦可用于添加类方法。 

 
classRubyist 
end 
   
Rubyist.instance_evaldo 
  defwho 
    "Geek" 
  end 
end 
   
puts Rubyist.who# => Geek 
 
 
const_get, const_set 

类似的,const_get和const_set用于操作常量。const_get返回指定常量的值: 
 
puts Float.const_get(:MIN)# => 2.2250738585072e-308 

const_set为指定的常量设置指定的值,并返回该对象。如果常量不存在,那么他会创建该常量,就是下面示范的那样: 
 
classRubyist 
end 
puts Rubyist.const_set("PI",22.0/7.0)# => 3.14285714285714 
 
  因为const_get返回常量的值,因此,你可以使用此方法获得一个类的名字并为这个类添加一个新的实例化对象的方法。这样使得我们有能力在运行时创建类并实例化其实例。 
 
# Let us call our new class 'Rubyist' 
# (we could have prompted the user for a class name) 
class_name ="rubyist".capitalize 
Object.const_set(class_name,Class.new) 
# Let us create a method 'who' 
# (we could have prompted the user for a method name) 
class_name =Object.const_get(class_name) 
puts class_name# => Rubyist 
class_name.class_evaldo 
  define_method:whodo|my_arg| 
    my_arg 
  end 
end 
obj = class_name.new 
puts obj.who('Matz')# => Matz