This file, testrequire.rb , has the following code:
require ‘string_extensions’
puts “This is a test”.vowels.join(’-’)
This file, string_extensions.rb , has the following code:
class String
def vowels
self.scan(/[aeiou]/i)
end
end
I run testrequire in Command Prompt, I get: internal:lib/rubygems/custom_require:29:in require': no such file to load -- string_extensions (LoadError) from <internal:lib/rubygems/custom_require>:29:inrequire’
from O:/Ruby/Practice/testrequire.rb:1:in `’
Sam R. wrote in post #1030126:
If you’re not on 1.9.2 and don’t have require_relative, I believe this
require ‘./string_extensions’
The problem with doing something like this is that the requiring file
will only find the required file when the program’s invoked from that
directory. For example, if you move back one directory and then try to
run it, it won’t work.
It’s a good idea to make scripts as portable as possible, so something
like this would be a good idea, I think.
What this means: FILE is a string of the current filename
File.dirname(f) gets the directory of f
File.expand_path(f) expands things like “~” and “.”
File.join(*files) joins all the files with whatever file separating
character is appropriate on your system. Ex: ‘/’, ‘’
As much as this might seem like overkill, it might be a good habit
to get into because LoadErrors are annoying as hell.
And yeah, on Ruby >= 1.9, require_relative does all this for you.