ファイルを取り出して自分のプログラムに読み込んで文字に分割し、結果の文字配列を多次元配列に分割したいそれぞれ5,000文字を入力し、それぞれの配列を同じ場所にあるファイルに書き込みます。Rubyで多次元配列を別々のファイルに書き込んでから順番に読む方法
ファイルを取得して読み込み、多次元配列を作成しました。ここでは、それぞれ別々の1次元配列を別々のファイルに書きたいと思います。
ファイルは、ユーザー入力によって入手されます。次に、最初のミックスインの配列にファイルを保存するチェーンヘルパーメソッドを作成し、これを多次元配列に分解する別のメソッドに渡して、最終的に現在セットアップされているチェーンの最後に渡します私はこれらのファイルを置く新しいディレクトリを作成します。
require 'Benchmark/ips'
file = "C:\\test.php"
class String
def file_to_array
file = self
return_file = File.open(file) do |line|
line.each_char.to_a
end
return return_file
end
def file_write
file_to_write = self
if Dir.exist?("I:\\file_to_array")
File.open("I:/file_to_array/tmp.txt", "w") { |file| file.write(file_to_write) }
read_file = File.read("I:/file_to_array/tmp.txt")
else
Dir.mkdir("I:\\file_to_array")
end
end
end
class Array
def file_divider
file_to_divide = self
file_to_separate = []
count = 0
while count != file_to_divide.length
separator = count % 5000
if separator == 0
start = count - 5000
stop = count
file_to_separate << file_to_divide[start..stop]
end
count = count + 1
end
return file_to_separate
end
def file_write
file_to_write = self
if Dir.exist?("I:\\file_to_array")
File.open("I:/file_to_array/tmp.txt", "w") { |file| file.write(file_to_write) }
else
Dir.mkdir("I:\\file_to_array")
end
end
end
Benchmark.ips do |result|
result.report { file.file_to_array.file_divider.file_write }
end
test.phpを
<?php
echo "hello world"
?>
私は、コアクラスをmonkeypatchしないことをお勧めします。ビジネスロジックをカプセル化したクラスを用意してください。コードを読みやすくします。 また、Rubyの 'String'はすでに配列として扱うことができます。ですから、文字列をファイルから5000文字の文字列に分割し、以下に示すようにファイルに書き込んでください。 – Uzbekjon
クラスに入れると、文字列と配列の処理エラーを防ぐことができますか? –
質問を理解できませんでした。あなたのコードはあらゆるエラーを処理できますか? – Uzbekjon