sample.rb
File.open("in.txt",'r:UTF-8'){|f| # r: 読み込み (省略可),
# r:Shift_JISなどとすればエンコーディング指定可能
puts f.read
}
File.open("in.txt"){|f|
f.each_line do |line|
puts line
end
}
File.open("in.txt"){|f|
f.each_char do |char|
print char
end
}
File.open("in.txt"){|f|
f.each_byte do |byte|
print byte
end
puts
}
f = File.open("in.txt")
p f.readline
f.each_char do |char|
print char
end
f.close
in.txt
First line.
Second line.
出力例
$ ruby sample.rb
First line.
Second line.
First line.
Second line.
First line.
Second line.
701051141151163210810511010146108310199111110100321081051101014610
"First line.\n"
Second line.
sample.rb
ARGF.each_line do |line|
print line.gsub(/line/, 'sentence')
end
in.txt
First line.
Second line.
in2.txt
Third line.
Fourth line.
出力例
$ ruby sample.rb in.txt in2.txt
First sentence.
Second sentence.
Third sentence.
Fourth sentence.
File.open("out.txt", 'w'){|f| # w:書き込み, a:追記
# w:Shift_JISなどとすればエンコーディング指定可能
f.puts "hi"
}
... {|f|
...
}
という部分は、すべて
... do |f|
...
end
と記載可能です。