Including Files in Ruby Questions
Question
- I am very new to Ruby so could you please suggest the best practice to separating files and including them.
- What is the preferred design structure of the file layout. When do you decide to separate the algorithm into a new file?
- When do you use load to include other files and when do you use require?
- And is there a performance hit when you include files?
Thanks.
Solution
I make one file per class, except classes that are small helper classes, not needed by other files. I separate my different modules in subdirectories also.
The difference between
load
andrequire
isrequire
will only load the file once, even if it's called multiple times, whileload
will load it again regardless of whether it's been loaded before. You'll almost always want to userequire
, except maybe inirb
when you want to manually want to reload a file.I'm not sure on the performance hit. When you
load
orrequire
a file, the interpreter has to interpret the file. Most Ruby's will compile it to virtual machine code after being required. Obviously,require
is more performant when the file may have already been included once, because it may not have to load it again.