From the current working directory I am trying to rename a file which is in another directory. My test IRB code is below:
C:\Documents and Settings\peter>irb
irb(main):001:0> Dir.pwd
=> "C:/Documents and Settings/peter"
irb(main):002:0> File.rename('C:\Documents and Settings\peter\My Documents\userdata\test.txt','a.txt')
=> 0
irb(main):003:0>File.exist?('C:\Documents and Settings\peter\My Documents\userdata\test.txt')
=> false
irb(main):004:0>File.exist?('C:\Documents and Settings\peter\My Documents\userdata\a.txt')
=> false
irb(main):005:0>
Instead of renaming the target file is getting deleted from the file system – why so? If it is not the right approach to rename a file, please advice me a safe approach. But I can’t change the current working directory for renaming, and to rename if I need to change the current directory,after renaming I want to get back the previous current working directory.
First, you should not use backslashes here. The reason for this is that backslash is an escape sequence initiator, so you might get very unexpected results next time (if you accidentally use backslashes in a double-quoted string, for example). In this case there were no problems, but it’s a dumb luck. Always use forward slashes in file paths. ruby on windows should handle them just fine.
Second, you’re looking in the wrong place. Renamed file should appear at
Because this is your current working dir. If you want it to appear in “C:/Documents and Settings/peter/My Documents/userdata” either change the working dir before renaming, or specify a full target file path.
You can also use a block with Dir::chdir.
After block returns, working dir is restored to whatever it was before
chdircall.