Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to call function before it is defined?

In my seeds.rb file I would like to have the following structure:

# begin of variables initialization
groups = ...
# end of variables initialization
check_data
save_data_in_database

# functions go here
def check_data
  ...
end
def save_data_in_database
  ...
end

However, I got an error because I call check_data before it is defined. Well, I can put the definition at the top of the file, but then the file will be less readable for my opinion. Is there any other workaround ?

like image 314
Misha Moroshko Avatar asked Apr 21 '11 12:04

Misha Moroshko


People also ask

Can you call a function before defining it?

It is not possible. Python does not allow calling of a function before declaring it like C.

What happens when you call a method in Ruby?

In ruby, the concept of object orientation takes its roots from Smalltalk. Basically, when you call a method, you are sending that object a message. So, it makes sense that when you want to dynamically call a method on an object, the method you call is send . This method has existed in ruby since at least 1.8.

Can you call a function before it has been defined PHP?

You cannot call undefined function, it will raise a fatal error. although in procedural code it can be called and afterwards defined.


1 Answers

In Ruby, function definitions are statements that are executed exactly like other statement such as assignment, etc. That means that until the interpreter has hit your "def check_data" statement, check_data doesn't exist. So the functions have to be defined before they're used.

One way is to put the functions in a separate file "data_functions.rb" and require it at the top:

require 'data_functions'

If you really want them in the same file, you can take all your main logic and wrap it in its own function, then call it at the end:

def main
  groups =  ...
  check_data
  save_data_in_database
end

def check_data
  ...
end

def save_data_in_database
  ...
end

main # run main code

But note that Ruby is object oriented and at some point you'll probably end up wrapping your logic into objects rather than just writing lonely functions.

like image 135
Brian Hempel Avatar answered Sep 28 '22 12:09

Brian Hempel