Tbpgr Blog

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

Ruby | File | dirname

概要

File.dirname

詳細

ディレクトリパスを取得する(絶対、相対双方)

サンプル

コード

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

# encoding: utf-8

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

filenames = ['sample1.txt', 'sample2.txt']
Dir.mkdir('tmp') unless File.exists?('tmp')
puts File.dirname(filenames[0])
puts File.dirname(__FILE__)
Dir.chdir('tmp')
puts File.dirname("../#{filenames[0]}")
puts File.dirname(__FILE__)
出力
.
C:/tmp
..
C:/tmp