找出放置文件的目录的名称
figure out name of directory where file is placed
例如我有这个目录结构:
DIRECTORY_A/cat/myfile.txt
DIRECTORY_B/dog/myfile.txt
DIRECTORY_C/tiger/myfile.txt
你可以看到,在每个目录中我都有相同的文件"myfile.txt"。 "myfile.txt" 是由 ruby 脚本创建的,如下所示。现在我想在 myfile.txt 中输入 myfile.txt 所在的目录名称。
因此,例如:
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"
不知道该怎么做。用什么代替“????”如我的代码所示:
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 "????"
有什么想法吗?
听起来您想从路径中提取最后一个目录名。最简单的方法是使用 File.dirname 和 File.basename:
last_dir = File.basename(File.dirname(path))
File.open(path,'w+') { |f| f.puts lastdir }
例如我有这个目录结构:
DIRECTORY_A/cat/myfile.txt
DIRECTORY_B/dog/myfile.txt
DIRECTORY_C/tiger/myfile.txt
你可以看到,在每个目录中我都有相同的文件"myfile.txt"。 "myfile.txt" 是由 ruby 脚本创建的,如下所示。现在我想在 myfile.txt 中输入 myfile.txt 所在的目录名称。
因此,例如:
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"
不知道该怎么做。用什么代替“????”如我的代码所示:
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 "????"
有什么想法吗?
听起来您想从路径中提取最后一个目录名。最简单的方法是使用 File.dirname 和 File.basename:
last_dir = File.basename(File.dirname(path))
File.open(path,'w+') { |f| f.puts lastdir }