Ruby: How to call function before it is defined?

后端 未结 5 1919
星月不相逢
星月不相逢 2021-01-11 10:08

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

# begin of variables initialization
groups = ...
# end of variables initializa         


        
5条回答
  •  花落未央
    2021-01-11 11:02

    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.

提交回复
热议问题