2012-04-20 52 views
0

如何在不使用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 

回答

3

這是否令人滿意?

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