Tbpgr Blog

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

Ruby | File | basename

概要

File.basename

詳細

指定ファイルのファイル名を返します。
第二引数に拡張子を指定した場合は、拡張子が省略されます。

サンプル

コード
# encoding: utf-8

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

filename = 'sample.txt'

create_file filename, <<EOS
内容1_1
内容1_2
内容1_3
EOS
puts File.basename('sample.txt')
puts File.basename('sample.txt', '.txt')
出力
sample.txt
sample