I have for example this directory structure:
DIRECTORY_A/cat/myfile.txt
DIRECTORY_B/dog/myfile.txt
DIRECTORY_C/tiger/myfile.txt
you can see, in each directory I have the same file "myfile.txt". The "myfile.txt" is created by ruby script as shown below. Now I would like to put in myfile.txt the directory name where myfile.txt is located.
So for example, the:
myfile.txt from "cat" directory should contain the string "cat"
myfile.txt from "dog" directory should contain the string "dog"
myfile.txt from "tiger" directory should contain the string "tiger"
Don't know how to to this. What to put instead the "????" as shown in my code:
def create_file
Dir['DIRECTORY_*/*/'].each do |dir|
File.new File.join(dir, 'myfile.txt'), 'w+'
Dir['DIRECTORY_*/*/myfile.txt'].each do |path|
File.open(path,'w+') do |f| f.puts "????"
Any idea?
答案 0 :(得分:0)
It sounds like you want to extract the last directory name from the path. The easiest way of doing that is to use File.dirname and File.basename:
last_dir = File.basename(File.dirname(path))
File.open(path,'w+') { |f| f.puts lastdir }