〜を指定した場合のファイル作成方法

ファイル名に〜(ホームディレクトリ)を指定した場合、以下のようにエラーになってしまいます。

サンプルスクリプト

filename = '~/file.txt'
f = File.open(filename, 'w')
f.puts("hello world")
f.close
$ ruby file_err.rb 
file_err.rb:2:in `initialize': No such file or directory - ~/file.txt  (Errno::ENOENT)
        from file_err.rb:2:in `open'
        from file_err.rb:2

このような場合は、絶対パスを取得できるexpand_pathメソッドを利用します。

expand_pathを利用したサンプルコード

filename = '~/file.txt'
f = File.open(File.expand_path(filename), 'w')
f.puts("hello world")
f.close

実行結果

$ ruby file_expand_path.rb 
$ cat file.txt 
hello world

添付ファイル: filefile_err.rb 540件 [詳細] filefile_expand_path.rb 552件 [詳細]

トップ   編集 凍結 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2025-03-12 (水) 11:47:43