I had the impression that I should use require 'some_path' to get a file or a library I want to use, but I couldn't get it to work, and load 'some_path' worked.
When are the different times when I should use these?
Also, is it possible to import a directory with the load or require commmands? I am trying to use a whole directory, but so far I could only get one file at a time with load.
You can use Dir to list all the files ending with .rb and require/load them
Dir["/path/to/dir/*.rb"].each { |file| load_your_file_here(file) }
I recommend requiring file and then including the module that file loads... If you are not using module or class inside your file than maybe you should reconsider your structure.
load might have some unintended consequences and it's not performant.
Once you call require for a file further calls of require will no longer require it again(i.e. will have no effect), while load will reload it every time you call it. As far as I know there is no way to load a whole directory.
Related
I'm trying to figure out what it means to require files, how to require files/gems/etc. I was trying to load a file in IRB, and got this piece of code (a dice generator):
LoadError: cannot load such file -- .d6.rb
from C:/Ruby22-x64/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from C:/Ruby22-x64/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from (irb):14
from C:/Ruby22-x64/bin/irb:11:in `<main>'
What does this code mean?
How can I assist loading files in IRB?
What does it mean to require files?
I assume the term "require" means to "load", but I'm at a loss as to what the mechanics are or where the files are actually located.
The file is located on my hard drive in my Ruby Projects folder:
C:\Ruby\d6\d6.rb
What I'd posted was "irb(main):013:0> require './d6.rb'" I'm not familiar with the require_relative command (again, very new to Ruby!). I would post the content of the file but I've been continuing to work on it and I didn't think to save a backup copy of what I'd been trying to load at the time. I guess I shouldn't have included the .rb extension? Ruby loads that by itself?
Also, I guess a side question would be: after looking in C:/Ruby22-x64/lib/ruby/2.2.0/ I don't have the "rubygems" folder or the rest of the filepath listed in the error message. I'm assuming that's a bad thing?
a)what this code means,
If you mean "this error code", it is complaining that it can't find the d6.rb file, presumably after you did require 'd6'.
b)how to assist loading files in IRB?,
Not sure what this means.
c)what does it mean to require files? I assume the term "require" essentially just means to "load", but I'm at a loss as to what the mechanics are or where the files are actually located
Basically, yes, load - but only once. If a file has been required, you can't require it again (or more precisely you can but nothing will happen, and you get false instead of true from require).
As to where they are loaded from, the list of directories Ruby searches when you require is in $LOAD_PATH. When you do require 'd6', only those directories are searched. When you require './d6, it will be loaded from the current directory. When you require_relative 'd6', it will be loaded from the directory the current file is in.
EDIT: Correction thanks to Jörg W Mittag.
I assume the term "require" means to "load", but I'm at a loss as to what the mechanics are or where the files are actually located.
require causes the ruby parser to read and execute the file. Normaly this is used to load additional modules and classes which then could be used to extend your app code functionality.
See Kernel#require to get more information about the load mechanics. See also Kernel#require_relative.
I'm new to Ruby
MakModule.rb
module Display
class Multiply
def Multiply.mul(first, second)
return first * second
end
end
end
MakRequire1.rb
require "Display"
puts Multiply.mul 5,6
MakRequire2.rb
require "MakModule.rb"
puts Multiply.mul 5,6
both file give me the error below
ruby: No such file or directory -- makRequire (LoadError)
How should I correct my code?
It is simply impossible that the code you posted here generates that error message. The error message says that you tried to require a file named makRequire, but that filename doesn't appear anywhere in the code you posted.
Without the actual code that is generating the actual error, it is impossible to answer your question. However, here are a few general tips:
Whenever the computer tells you that it cannot find something, in 99% of the cases, the problem is that the thing the computer tells it couldn't find isn't actually there.
So, in this case, the computer tells you that it cannot find a file named makRequire.rb, and the most likely explanation for that is that makRequire.rb doesn't actually exist. So, the first thing you need to check is: does makRequire.rb (note the capitalization and the file extension) actually exist? Because if it doesn't exist, then the reason why the computer cannot find it, should be rather obvious.
In 99% of the rest of the cases, the problem is that the thing the computer is looking for does exist, but the computer is looking in the wrong place. So, after you have verified that makRequire.rb actually does exist, you need to make sure that the directory the file is in, is in Ruby's $LOAD_PATH, and if it isn't, you need to add that directory to Ruby's $LOAD_PATH. Alternatively, if you want to require the file relative to the path of the file that is doing the requiring, you need to use require_relative instead of require.
The third thing to check for, is whether the user who own the ruby process has sufficient privileges to access the file makRequire.rb, the directory it is in and all of its parent directories.
Try this,
require File.join(File.dirname(__FILE__),'MarkModule')
Try require './MakModule', because the . is the current directory.
require 'MakModule'
You can require a file that is in the same directory. To use a module you would typically include the module inside a class definition. So you would never require Display, you would require the file that contains Display (without the .rb extension, usually).
I have a bunch of different .rb command line script files that perform various tasks, but they all use the same database.
I'm coding the 2nd .rb file, and the 1st one has all references to ActiveRecord, db connections, and classes that represent my models etc.
Is it possible to move all this to another file, and then just import the file in each of my .rb files?
How would this work?
require basically goes out and runs another file in the context of the current ruby process if it hasn't be required yet. if your db file is called models.rb and it is living in a sub directory called lib, it would look like this
require 'lib/models'
You need to read Modules, which is part of the "Pickaxe Book", AKA Programming Ruby.
Using Mechanize with Ruby I get a certain file using agent.get('http://example.com/foo.torrent'), with FileUtils or otherwise, how do I save this file to my hard drive (for instance, in a directory wherefrom the script is running)?
P.S. class => WWW::Mechanize::File
Well, WWW::Mechanize::File has a save_as instance method, so I suppose something like this might work:
agent.get('http://example.com/foo.torrent').save_as 'a_file_name'
Please note that the Mechanize::File class is not the most appropriate for large files. In those cases, one should use the Mechanize::Download class instead, as it downloads the content in small chunks to disk. The file will be downloaded to where the script is running (although you can specify a different path as well). You need to set the default parser first, create a new one or modify an existing parser. Then, save it to the desired path:
agent.pluggable_parser.default = Mechanize::Download
agent.get( "http://example.com/foo.torrent}").save("path/to/a_file_name")
Check here and here for more details. Also, there's a similar question here in Stackoverflow.
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.
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 and require is require will only load the file once, even if it's called multiple times, while load will load it again regardless of whether it's been loaded before. You'll almost always want to use require, except maybe in irb when you want to manually want to reload a file.
I'm not sure on the performance hit. When you load or require 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.