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
fibmethod that includes the current object on whichfibis defined. So, it finds the current definition offiband invokes it.I mention the current part because if the
fibmethod redefinedfibon 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.