Ruby

Published at 2026/03/28

Ruby

basename

path = "/home/user/documents/report.pdf"

# ファイル名全体を取得
p File.basename(path) 
# => "report.pdf"

# 拡張子を除いて取得
p File.basename(path, ".pdf")
# => "report"

# 拡張子が不明な場合、ワイルドカードを使って取り除く
p File.basename(path, ".*")
# => "report"

regex

メタ文字をエスケープする

text = 'be\|fore'
p text.gsub(/(?<!\\)\|/, '\|')
=> "be\\|fore"

文字列から日付を取り出す

str = "2023-02-02-01-title"
file_date = str.match(/\d{4}-\d{2}-\d{2}/){\|s\| Date.strptime(s.to_s, '%Y-%m-%d')}
p file_date.to_s
# => "2023-02-02"