On Jul 30, 2004, at 7:31 AM, Lloyd Zusman wrote:

> Is there a way to define forward references to functions?  Due to my 
> own
> personal eccentricities, I like to have the main body of a program
> appear at the top of its source file, and the functions it uses at the
> end.
>
> By "define forward reference", I mean something analogous to the
> following C construct:
>
>   static char* foo();  /* forward reference */
>   static char* bar();  /* forward reference */
>
>   main () {
>     printf("%s\n", foo());
>     printf("%s\n", bar());
>     exit(0);
>   }
>
>   char* foo() {
>     return ("foo");
>   }
>
>   char* bar() {
>     return ("bar");
>   }
>
> If I could make use of forward references in ruby, the above program
> could look something like this:
>
>   # somehow, define a forward reference to function foo()
>
>   # somehow, define a forward reference to function bar()
>
>   # program starts here
>
>   x = foo()
>   y = bar()
>   puts x
>   puts y
>   exit(0)
>
>   # real function definitions ...
>
>   def foo
>     return "foo"
>   end
>
>   def bar
>     return "bar"
>   end
>
> Am I totally out of luck, or is there some kind of ruby trick I can
> perform which will give me this capability?

One other way is to use blocks:

# code that does this:
def chunk(&block) ($CHUNKS||=[]) << block end
END{ $CHUNKS.reverse_each{|ch| ch[] } }
# end special code :)

chunk do

   x = foo()
   y = bar()
   puts x
   puts y
   exit(0)

end

chunk do

   def foo
     return "foo"
   end

   def bar
     return "bar"
   end

end

Of course, you'd name it something other than chunk. And there's probly 
a one liner for it, too, but I didn't have enough time to clean it up 
much.

cheers,
Mark