I got a method where I use Dir.chdir(File.dirname(__FILE__))
inside. I am using it so that I can run the ruby file from anywhere and not get this error: No such file or directory @ rb_sysopen - 'filename' (Errno::ENOENT)
.
Using the method for the first time works fine but using it for the second time throws an error. See method and exact error below.
def meth(string)
Dir.chdir(File.dirname(__FILE__))
hash = JSON.parse(File.read("file.json"))
# do something with hash and string
# return some value
end
meth("first string") # this returns what is expected
meth("second string") # this second usage of the method throws the error
Error sample pinpointing the line where I used Dir.chdir(File.dirname(__FILE__))
:
dir/decoder.rb:44:in `chdir': No such file or directory @ dir_s_chdir - lib (Errno::ENOENT)
Not sure if OS plays a role here, I am using an m1 BigSur on version 11.2.3.
- Why is this happening?
- What needs to be done so that the method` can be used as much as needed without running into the error?