如何根据用户的输入使用别名方法

问题描述:

如何在不使用eval的情况下更改以下代码。有没有一种方法可以在初始化Heap时根据参数来别名getroot函数。如何根据用户的输入使用别名方法

class Heap 

    def initialize arr,type=:min 
    newfunc = "get#{type.to_s}".to_sym 
    eval ("class << self; alias #{newfunc} :getroot; end") 
    end 

    def getroot  
    puts "Inside Getroot" 
    end 

end 

a = Heap.new([1,2,3],:max) 
a.getmax      #prints Inside Getroot 

b = Heap.new([1,2,3],:min) 
b.getmin      #prints Inside Getroot 

这是否令人满意?

class Heap 
    def initialize arr, type=:min 
    newfunc = "get#{type.to_s}".to_sym 
    self.class.class_eval {alias_method newfunc, :getroot} 
    end 
    def getroot 
    puts "Inside Getroot" 
    end 
end 
+0

Thankz Rachel。这是我寻找的。 – ramz 2012-04-20 02:24:27