Ruby:◇ファイル操作:ファイル入力 ・・・ 【Ruby:22歩目】
◇ファイル操作:ファイル入力
※久しぶりの Ruby学習。
しかしなんとものんびりしたスピード。1年かかりそうだな、本1冊。
・(前回はこちら)
(やっとこさ、)今回から「ファイル操作」に入る。楽しみではある・・・
追記に ▼
PHPなどとの違いを考慮しつつ、ゆっくりと
良書「はじめてのRubyプログラミング
学んでゆく、詳細な記録です。
(本日の参照:208頁)



【ミッション】
◆テキストファイルの読込
※テキストファイルの読込
Hello World! はつまらないので
Change The World と書いたテキストファイルを用意。
(あんま、関係ないけど)change.txt
text = File.read('change.txt')
puts text #=> Change The World・File クラス の
read メソッド を利用しているわけだ。
これは、テキストファイルの全体を
・そのまま 読み込む。
では、行ごとに読み込むには?
(実際はこれが一番多い利用ケース となるだろう)
※テキストファイルに、Change The Worldの歌詞を
書いておいて
If I can reach the stars,
Pull one down for you,
Shine it on my heart
So you could see the truth:
That this love I have inside
Is everything it seems.
But for now I find
It's only in my dreams.
And I can change the world,
I will be the sunlight in your universe.
You would think my love was really something good,
Baby if I could change the world.
lines = File.readlines('change.txt')
lines.each_with_index do |line,i|
print "#{i + 1}: #{line}"
end結果は
1: If I can reach the stars,
2: Pull one down for you,
3: Shine it on my heart
4: So you could see the truth:
5:
6: That this love I have inside
7: Is everything it seems.
8: But for now I find
9: It's only in my dreams.
10:
11: And I can change the world,
12: I will be the sunlight in your universe.
13: You would think my love was really something good,
14: Baby if I could change the world.
こうなる。
・File クラス の
readlines メソッド
これが、1行ごとの読込をしてくれる
・lines は、配列変数で、
each_with_index でループさせているわけだ。
◆ディレクトリ付きのパス
※change.txtは、ソースファイルと同じところにおいたが
当然実際の利用では、場所を指定することが
多くなるはずだ。
・change.txt を datas というフォルダに
入れた場合は、
lines = File.readlines('datas/change.txt')となる >>理解
◆ファイルが無いときは?
※該当するファイルが存在しないとき
パスが違っている場合のエラーは
20090107.rb:8:in `read': No such file or directory - change_no.txt (Errno::ENOENT)
from 20090107.rb:8
こんな感じ。
エラートラップはこのように行う。
text = ''
fname = 'data/change.txt'
begin
text = File.read(fname)
rescue
puts "ファイル:<#{fname}>の読込に失敗!"
end
※ rescue ってのがいいな。
+++++++++++++
【PHPだと?】
+++++++++++++
・まずファイルの読込は
$tar_file = "datas/change.txt";
$fp_in = fopen($tar_file,'r');
if (!$fp_in) {
}else{
# 処理
}
・読み込んでおいて行ごとに
$tempKugiri="\t";
while ($data = fgetcsv ($fp_in, 9999, $tempKugiri)) {
$allcnt_data=count($data);
}
ってやることが多い。
・ファイル有無はこれら実行する前に
if(file_exists($tar_file)){}で調べることが多いな。
なんか、Ruby って
・シンプルでスマート って感じだなぁ。










