1

I have a .rb script that access and edit all .txt files in same directory with Dir.glob('*.txt') do |rb_file|

If I call it from terminal ruby myscript.rb all works fine.

Then I made an executable, launched with double click on Mac OS, as explained at this and this answers. I started file with #!/usr/bin/env ruby, gave permissions chmod +x myscript.rb, and opened it with terminal.

Ruby is working but when I try to access files in the same directory, the script can't find them. In fact, the script look for these files in /Users/myname directory.

How can I access the original directory where the double clicked file is?

I tried with ./ without success. Absolute path is not an option, unless programmatically retrieved.

Thank you

Community
  • 1
  • 1
Karlooie
  • 163
  • 1
  • 7

2 Answers2

0

If I understand you right, you should be able to use this to get the directory the ruby script is in regardless of how you invoke it.

File.dirname(File.expand_path(__FILE__))

If I make a simple script that simply puts the above and place it in ~/tmp/foo.rb this is the output. My prompt is my current directory followed by a '$'. In every case the same value is returned.

~/tmp $ ruby foo.rb
/Users/philip/tmp
~ $ ruby tmp/foo.rb
/Users/philip/tmp
~ $ ruby /Users/philip/tmp/foo.rb
/Users/philip/tmp
~ $ cd /
/ $ ruby /Users/philip/tmp/foo.rb
/Users/philip/tmp
Philip Hallstrom
  • 19,673
  • 2
  • 42
  • 46
0

There is a method Kernel#__dir__ which returns the directory of the file the call to __dir__ is in. (It is basically equivalent to File.dirname(File.realpath(__FILE__)).)

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653