Rubyファイルを簡単に読み込む
1138 ワード
キーボード入力を取得し、出力する
行ごとにファイルの内容を読み込む
行ごとにファイルを読み取る、作成した文字列に従って分割する.本稿ではe文字で分割する
IOを使用する.foreach読み取りファイル
読み込んだファイルを1つの文字列に保存できます
読み込んだファイルを1つの配列に保存することもできます
while line = gets
puts line
end
行ごとにファイルの内容を読み込む
File.open("E:/workspaceNew/RubyStudy/test.txt") do |file|
file.each_line{|line| puts "Got #{line.dump}"}
file.close();
end
行ごとにファイルを読み取る、作成した文字列に従って分割する.本稿ではe文字で分割する
File.open("E:/workspaceNew/RubyStudy/test.txt") do |file|
file.each_line("e"){|line| puts "Got #{line.dump}"}
file.close();
end
IOを使用する.foreach読み取りファイル
IO.foreach("E:/workspaceNew/RubyStudy/test.txt"){|line| puts line};
読み込んだファイルを1つの文字列に保存できます
str = IO.read("E:/workspaceNew/RubyStudy/test.txt");
puts str.length;
puts str[0,30]
読み込んだファイルを1つの配列に保存することもできます
arr = IO.readlines("E:/workspaceNew/RubyStudy/test.txt")
puts arr.length;
puts arr[0]