Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stack level too deep (SystemStackError) while using class_eval ruby

Tags:

ruby

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
like image 711
vishal Avatar asked Mar 21 '26 14:03

vishal


1 Answers

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.

like image 128
sepp2k Avatar answered Mar 23 '26 05:03

sepp2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!