#navi(../)
* 〜を指定した場合のファイル作成方法 [#a0364f63]
ファイル名に〜(ホームディレクトリ)を指定した場合、以下のようにエラーになってしまいます。

#contents
#htmlinsertpcsp(ll-top.html,ll-sp.html)

* サンプルスクリプト [#ja6888ed]
#ref(file_err.rb)
 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を利用したサンプルコード [#w65be673]
#ref(file_expand_path.rb)
 filename = '~/file.txt'
 f = File.open(File.expand_path(filename), 'w')
 f.puts("hello world")
 f.close

** 実行結果 [#r6cdc8fa]
 $ ruby file_expand_path.rb 
 $ cat file.txt 
 hello world

#htmlinsertpcsp(ll-btm.html,ll-sp.html)

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS