Steven LeBeau wrote:
> Hi,
> 
> I'm currently taking a beginning C++ class and learning Ruby on my own.
> 
> One thing I'm curious about (but don't have the vocabulary to articulate it
> to a search engine, apparently) is if there's an equivalent to declaring
> functions and then defining them later in the file so you don't have to
> worry about where the function is in relation to another function that calls
> it (or is called by it). In Ruby, I guess I'm talking about methods rather
> than functions, but the same principle: is there a way for method x to call
> method y (which appears later on in the program) by having declaration
> statements at the top of your program? (I think that time my question may
> have made more sense).
> 
> This wasn't addressed on the Ruby webpage on the "Ruby From C and C++" page
> as being a "difference" or a "similarity".
> 
> -Steven
> 
> P.S.--I'm new. Hi!
> 

Hi, welcome to ruby!

In ruby, there is no need to declare a function before the compiler sees 
it, only before your program calls it. If your functions are all in 
classes or modules, you rarely need to think about how they are ordered 
in files.

The case where order matters is when you have a function called directly 
from a script file, as you would if you were writing a script to be 
called from the command line (rather than a library). In that case, 
there is a trick that you can use to call a function above where it is 
defined, if you prefer. You can use the BEGIN construct to designate a 
block to be evaluated after the file is parsed, but before anything else 
in the file is executed:

####################
main

BEGIN {
   def main
     puts "Hello, world."
   end
}
####################

There is also an END construct, which you can use to get the same effect:

####################
END {
   main
}

def main
   puts "Hello, world."
end
####################

Without any special trickery, you would have to put the main call below 
the definition, which arguably obscures the intent of the script. 
(There's no need to call the method "main"--that's just an example.)

HTH.

-- 
       vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407