2011-11-13 43 views
2

不明白爲什麼我在運行此程序時得到堆棧級別太深。堆棧級別太深(SystemStackError),而使用class_eval ruby​​

module A 
    class Fruit 

    def initialize 
     puts "pears" 
    end 

    [:orange, :apple].each do |fruit| 
     class_eval %Q{ 
      def #{fruit} 
       puts #{fruit} 
      end 
     } 
    end 

    puts "pineapple" 
end 

a_fruit = Fruit.new 
a_fruit.apple 
end 

another_fruit = A::Fruit.new 
another_fruit.orange 

該程序的輸出是

(eval):3:in `apple': stack level too deep (SystemStackError) 
    from (eval):3:in `apple' 
    from testquestion.rb:20 

回答

4

改變這一行從puts #{fruit}puts '#{fruit}'。由於此代碼位於類eval中,因此ruby認爲此行是調用方法,並嘗試一次又一次地調用您的#{fruit}(appleorange)方法。

8
class_eval %Q{ 
    def #{fruit} 
     puts #{fruit} 
    end 
} 

讓我們來看看這是什麼擴展爲fruit = :apple

def apple 
    puts apple 
end 

現在應該很清楚爲什麼會引起無限遞歸。

相關問題