I saw this example about the fibonacci sequence then tested it in IRB. Was hoping someone could break it down for me and show me how it's using the same method inside the method that is being defined.
def fib(n)
return n if (0..1).include? n
fib(n-1) + fib(n-2) if n > 1
end
When you define a method with def whatever(...) you are doing two things: creating a method, and assigning it to the named method slot.
When you invoke a method in Ruby it will look that up in the local scope; inside the fib method that includes the current object on which fib is defined. So, it finds the current definition of fib and invokes it.
I mention the current part because if the fib method redefined fib on the current object inside itself the new definition would be used, not the old definition.
That is to say: it will dynamically find the code associated with the name each time the name is invoked.
It is called recursion... It is a pattern that comes up in programming at times... If you want to program it is a tool/process you should learn. Instead of regurgitating here what is already out there, just read what is on wikipedia... Which contains an explanation of the fibonacci sequence which is the defacto example of recursion.
http://en.wikipedia.org/wiki/Recursion
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With