Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this method use its own method in ruby?

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
like image 619
ericraio Avatar asked Aug 28 '26 22:08

ericraio


2 Answers

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.

like image 127
Daniel Pittman Avatar answered Aug 31 '26 15:08

Daniel Pittman


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

like image 38
Jer In Chicago Avatar answered Aug 31 '26 15:08

Jer In Chicago



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!