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

1
  • Did you ever figure this out? Commented Oct 26, 2016 at 17:42

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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__)).)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.