As the subject states, I experienced a stack overflow when playing with singleton methods in IRB. Below is the code I’ve tried:
c= C.new
class << c
def class
"my class is #{self.class}."
end
end
When I called c.class, I got a:
SystemStackError: stack level too deep
Maybe IRB bug!
I found a reference on how to adjust stack sizes but don’t understand what stack sizes are in the first place.
Question:
Why did I get that error in IRB? Also, how can I continue experimenting with Ruby singleton/class methods?
First things first, there is some thing called
recursionwhere a function can call itself. This is what you have unintentionally done in your code.The second thing, the stack is something which maintains the function call trace. So that when end of recursion or stack level depth has been reached, it can correctly resume the program.
Its something like this:
Say you have function A and function B.
Your machine basically halts executing A, saves the state of variables in A onto a stack, calls and executes B. When finally B exits, it pops from the stack and resumes executing A.
In that specific example, since you wish to define your own
classmethod. The following code should do:Hope this helps.