Monday, March 7, 2011

Extraordinarily Simple Ruby Question: Where's My Class?

[I'm just starting with Ruby, but "no question is ever too newbie," so I trudge onwards...]

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

From stackoverflow
  • The easiest way is to put them both in the same file.

    However you can also use require, e.g.:

    require 'first_class'
    
    Yar : Cool, that worked, thanks very much.
  • You can also use autoload as follows:

    autoload :FirstClass, 'first_class'
    

    This code will automatically load first_class.rb as soon as FirstClass is used. Note, however, that the current implementations of autoload are not thread safe (see http://www.ruby-forum.com/topic/174036).

  • There's another point worth noting: you wouldn't typically use a main file in ruby. If you're writing a command line tool, standard practice would be to place the tool in a bin subdirectory. For normal one-off 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
    
    Yar : Hi ar2800276, thanks for that! In Java we have a static main method that can be put on any class. Is there some advantage to your "standard practice" way of doing this in Ruby?
    : >Is there some advantage to your "standard practice" way of doing this in Ruby? The advantage is that the static class method doesn't exist in Ruby :)
    Yar : Very cool. I don't know if I'll be doing any Ruby without Rails, anyway, but I do like to know the stuff just in case. Thanks again!
    Yar : Actually, the advantage of this idiom is so the `main` code doesn't run if the file is merely required.

0 comments:

Post a Comment