An unusually simple Ruby question: Where is my class?

[I’m just starting with Ruby, but “no one is too new”, so I dragged along ...]

Every tutorial and book I see goes from Ruby with an interactive shell to Ruby on Rails. I do not do Rails (yet), but I do not want to use an interactive shell. I have a class file (first_class.rb) and Main (main.rb). If I run main.rb, of course I get uninitialized constant FirstClass. How to tell ruby ​​about first_class.rb?

+3
source share
3 answers

The easiest way is to place them in a single file.

However, you can also use require, for example:

require 'first_class'
+8
source

You can also use autoload as follows:

autoload :FirstClass, 'first_class'

first_class.rb, FirstClass. , not (. http://www.ruby-forum.com/topic/174036.

+3

Another point worth noting: usually you do not use the file mainin ruby. If you are writing a command line tool, standard practice is to place the tool in a subdirectory bin. For ordinary one-time scripts, the main idiom is:

if __FILE__ == $0
  # main does here
  # `__FILE__` contains the name of the file the statement is contained in
  # `$0` contains the name of the script called by the interpreter
  # 
  # if the file was `required`, i.e. is being used as a library
  # the code isn't executed.
  # if the file is being passed as an argument to the interpreter, it is.
end
+2
source

All Articles