Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | File | expand_path

概要

File.expand_path

詳細

第1引数に指定したfilenameを絶対パスに展開する。
第2引数は省略するとカレントディレクトリを基準に。
指定した場合は、指定ディレクトリを基準にします。

サンプル

コード

カレントディレクトリがWindowsのC:\tmpだったとします。

# encoding: utf-8

def create_file(filename, contents)
  File.open(filename, 'w:utf-8') {|f|f.print contents}
end

filenames = ['sample1.txt', 'sample2.txt']
filenames.each {|f| create_file f, "test"}
Dir.mkdir('tmp') unless File.exists?('tmp')
p Dir.pwd
filenames.each {|f| p File.expand_path(f)}
Dir.chdir('tmp')
p Dir.pwd
filenames.each {|f| p File.expand_path(f, "../")}
出力
"C:/test"
"C:/test/sample1.txt"
"C:/test/sample2.txt"
"C:/test/tmp"
"C:/test/tmp/sample1.txt"
"C:/test/tmp/sample2.txt"
"C:/test/sample1.txt"
"C:/test/sample2.txt"