From: Brian Candler Date: 2007-03-12T18:13:23+09:00 Subject: Re: Newbie: def must come before call to def? On Mon, Mar 12, 2007 at 03:05:09PM +0900, planetthoughtful wrote: > In Ruby, am I required to put my defs before any code that calls those > defs? I'm porting general skills across from PHP, where you can put a > function statement anywhere in a program, and the interpreter will > load the entire file before looking for the function definition. > > In Ruby, it appears that defs have to come first? So, the following is > right: > > def beforecode > puts "appears before code that calls it" > end > > beforecode > > but this would be wrong? > > aftercode > > def aftercode > puts "appears after code that calls it" > end Yes. The reason is that unlike many other languages, Ruby does a lot more work at 'run time' - even defining methods and classes. This is one reason it's such a dynamic language. The first thing which Ruby does when reading in a source file is to "parse" it into a syntax tree - that is, it knows which things are expressions, which things look like "def function ... end" and so on. But it doesn't execute them. No classes are defined, no methods are defined. During the parse phase, the only errors you'll get are structural (e.g. your "end"s don't balance) Then it runs the code. If that code defines a method, then that method only gets defined when the definition is run. So if you write: aftercode def aftercode ... end then when line 1 is executed, it finds that no method 'aftercode' exists in the current object, so it aborts. HTH, Brian.