4

I've a small ruby program that require files in the same directory. Program works perfect on my mac and when I run a test ruby script without any require it also works so. It seems the ruby program doesn't look in the current directory for the file by default. e.g. the . dir. In windows where do I need to update this so ruby does look in the current dir for requires?

leeand00
  • 25,510
  • 39
  • 140
  • 297
Derek Organ
  • 8,323
  • 17
  • 56
  • 75
  • The original [select isn't broken](http://pragprog.com/the-pragmatic-programmer/extracts/tips) anecdote was about someone assuming that something was wrong with Windows. (The link is only to an explanation of "select isn't broken" - the anecdote is in the book itself) – Andrew Grimm Nov 18 '11 at 00:23
  • I own that book and have read it. Its really doesn't apply here. Ruby 'app' is surely portable between OS. I'd like to know is there a config setting somewhere for Ruby on windows that will automatically look in the local dir for required files. I'm not claiming there is a fault with the OS just a question on how to config – Derek Organ Nov 18 '11 at 01:49
  • 1
    @DerekOrgan: Just because there are runtimes for both platforms doesn't mean that the "app is surely portable between OS". When you take advantage of system-specific behavior, such as the library search path, you lose portability. And changing the ruby file to not rely on non-portable behavior is exactly the right solution. – Ben Voigt Nov 18 '11 at 02:27
  • Its a relative path specifically for the folder my ruby app is in not system specific. I accept that it was changed for a good reason but in general relative paths should be portable. – Derek Organ Nov 18 '11 at 02:39

3 Answers3

7

Chances are that your Mac is running Ruby 1.8 and Windows is running Ruby 1.9. As of 1.9, the default load path no longer includes the current directory. A common practice is to add this to the top of your ruby file before your require statements

$LOAD_PATH.unshift File.dirname(__FILE__)
require 'my_file.rb'

You can also use the shorthand $: instead of $LOAD_PATH:

$:.unshift File.dirname(__FILE__)

Another alternative is adding the load path on the command line instead:

ruby -I. my_ruby_file.rb
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
3

Ok, I understand now since 1.9.2 for "Security" reasons they don't allow require to work like that anymore. The neatest way I found to solve it strangely was to put './' in front of every require.

e.g.

require "./myfile.rb"
Derek Organ
  • 8,323
  • 17
  • 56
  • 75
0

"." was removed from $: was removed from Ruby 1.9.2 to be precise. Do

puts RUBY_VERSION
puts $:.inspect

on Ruby 1.8 (what's installed on your Mac) and Ruby 1.9.2 (what's installed on your windows machine) if you don't believe me.

Why does Ruby 1.9.2 remove "." from LOAD_PATH, and what's the alternative? discusses why "." was removed.

Community
  • 1
  • 1
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338