There are two ways to change the current working directory in Ruby, but you need to notice the thread-safe issue.
Dir.chdir
Dir.chdir is the most traight way:
|
If you need to go back to the previous directory:
|
Dir.chdir with block
A more idiomatic way is using a block to finish the task and go back to the previous directory:
|
The original working directory is restored when the block exits. The return value of chdir is the value of the block.
But, this is not thread-safe.
Dir.chdir will call the POSIX function to change the working dir of the current process, so it can never be made safe across threads.
MRI adds a warning message for this scenario, let’s run this code snippet:
|
The will be a warning message printed out:
|
How to be thread-safe
If you want to make this block to be safe-thread, you need to add Mutex for it:
|
Join my Email List for more insights, It's Free!😋