Last Updated: February 25, 2016
·
4.734K
· peterpengnz

Change file directory in ruby

In ruby, system command only executes command a subshell. Therefore, if you trying to execute some command in certain location you need to use '&&':

system('cd /Users/peterzhang/Downloads && pwd')

If you are going to run more command in that directory, it is better to change directory to there:

Dir.chdir('/Users/peterzhang/Downloads')

Then you can do any number of commands you need with system method:

system('pwd')
system('ls RailsCasts/')

2 Responses
Add your response

You do enclose the system() calls in a block to not tamper with the global working directory

Dir.chdir("foo") do
  system('pwd')
  system('ls RailsCasts/')
end

EDIT: Note this is NOT threadsafe.

over 1 year ago ·

nice!

over 1 year ago ·