Ruby の File クラスを使用して、ディレクトリが存在しない場合はどのように作成しますか? 質問する

Ruby の File クラスを使用して、ディレクトリが存在しない場合はどのように作成しますか? 質問する

私は次のように述べます。

File.open(some_path, 'w+') { |f| f.write(builder.to_html)  }

どこ

some_path = "somedir/some_subdir/some-file.html"

私が実現したいのは、パス内にsomedirまたはまたはその両方と呼ばれるディレクトリがない場合に、それを自動的に作成することです。some_subdir

どうやってやるの?

ベストアンサー1

親ディレクトリがまだ存在しない場合は、FileUtils を使用して再帰的に作成できます。

require 'fileutils'

dirname = File.dirname(some_path)
unless File.directory?(dirname)
  FileUtils.mkdir_p(dirname)
end

編集: コアライブラリのみを使用するソリューションを以下に示します (ホイールの再実装は推奨されません)

dirname = File.dirname(some_path)
tokens = dirname.split(/[\/\\]/) # don't forget the backslash for Windows! And to escape both "\" and "/"

1.upto(tokens.size) do |n|
  dir = tokens[0...n]
  Dir.mkdir(dir) unless Dir.exist?(dir)
end

おすすめ記事