2
votes

Dont understand why I am getting stack level too deep when I run this program.

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

The output of this program is

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

2 Answers

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

Let's look at what this expands to for fruit = :apple:

def apple
    puts apple
end

It should now be clear why that causes infinite recursion.

4
votes

Change this line from puts #{fruit} to puts '#{fruit}'. Because this code is located inside class eval, ruby considers this line the method calling and try to call your #{fruit} (apple or orange) method again and again.