From: Sebastian Hungerecker Date: 2009-04-10T05:25:34+09:00 Subject: Re: Calling a Function Before It's Defined Mark Bilk wrote: > I would like to be able to call a function (or a class, > when I get more object-oriented) earlier in the program > file than where I define it. Such a "top-down" layout > seems natural to me. In C I could use a function > prototype for this. The reason why you have to declare a function in C before you call it (before meaning the code position) is fundementally different from why you have to define it in ruby before you call it (here before means the runtime). Examples: def foo() bar end def bar() end foo Works just fine (because the code in foo that references bar executes after bar has been defined (even if it's position in the code is earlier). def foo() 1 end def bar() foo end bar #=> 1 def foo() 2 end bar #=> 2 You can redefine methods and ruby always executes the version of the method that's currently in existence. def foo() def bar() end end bar #error foo bar # Now it works You can define method a within method b. That will have the effect that after running method b, method a will be defined (although it wasn't before). You can also redefine methods that way: def foo() 1 end def bar() def foo() 2 end end foo #=> 1 bar foo #=> 2 All this has the effect that you can't forward declare methods like you can in C. If you do this: def foo() end foo def foo() bar end The call in line 2 will call the empty version of foo because that is the version currently in existence. HTH, Sebastian