Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Needing forward declaration in Ruby

I am trying to write a Ruby script in one file.

I would like to know if it is possible to write the "main" function in the beginning, having the other functions that are used by main, defined after it. In other words, I would like to call a not yet defined function, so that they do not depends on definition order. Just changing the order is not possible because it gives an "undefined method" error. In C/C++ we use forward declarations... is there something similar in Ruby or another solution to this?

like image 576
dbarbosa Avatar asked May 08 '10 15:05

dbarbosa


People also ask

Why do we need forward declaration?

A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier. In the case of functions, this allows us to tell the compiler about the existence of a function before we define the function's body.

How do I create a forward class declaration?

In C++, classes and structs can be forward-declared like this: class MyClass; struct MyStruct; In C++, classes can be forward-declared if you only need to use the pointer-to-that-class type (since all object pointers are the same size, and this is what the compiler cares about).

Where do you put forward declarations?

Generally you would include forward declarations in a header file and then include that header file in the same way that iostream is included.

When can you use forward declaration?

In C++, Forward declarations are usually used for Classes. In this, the class is pre-defined before its use so that it can be called and used by other classes that are defined before this. Example: // Forward Declaration class A class A; // Definition of class A class A{ // Body };


1 Answers

You just need the functions you call to be defined when your main function runs, not when it's defined. So, the easiest solution is to write the main function at the script's beginning, but call it at the end.

def main
  foo(42)
  bar(24)
end

# definitions of foo and bar

main
like image 100
Ash Wilson Avatar answered Oct 30 '22 06:10

Ash Wilson