0
私はRubyの初心者です。私は開いて、hasを作成して、ファイルをcsvファイルに読み込むファイルを持っています。さらなる処理のために。何らかの理由で、私はハッシュのすべてのエントリをファイルに入れて、正しい フォーマットにすることができません。列フォーマット。ハッシュとtxtファイルからRubyでCSVファイルを作成
これは、サンプルファイル
name: bc0090FB2.st.at.net
address: 192.168.1.2
state: 0
lastpingtime: 2013-02-13
name: bc0110FB2.st.at.net
address: 192.168.1.15
state: 1
lastpingtime: 2013-02-13
name: bc0150FB2.st.at.net
address: 192.168.1.12
state: 2
lastpingtime: 2013-02-13
name: bc0250FB2.st.at.net
address: 192.168.1.5
state: 3
name: bc0560FB2.st.at.net
address: 192.168.1.3
state: 1
lastpingtime: 2013-02-13
name: bc0058FB2.st.at.net
address: 192.168.1.4
state: 2
lastpingtime: 2013-02-13
name: bc0540FB2.st.at.net
address: 192.168.1.10
state: 3
lastpingtime: 2013-02-13
name: bc5890FB2.st.at.net
address: 192.168.1.6
state: 4
name: bc0520FB2.st.at.net
address: 192.168.1.8
state: 2
lastpingtime: 2013-02-13
これはそれはあなたが達成したいのか明確ではないのですサンプルコード
require 'csv'
splitup = {}
f = CSV.open("order3.txt", "r") do |fp|
fp.each do |line|
# Create a hash to capture each key value pair
(key, value) = line.chomp.split(":")
splitup[key] = value
namea = splitup["name"]
addressa = splitup["address"]
lastping = splitup["lastpingtime"]
statea = splitup["state"]
lineA = "#{namea} #{addressa} #{statea} #{lastping}"
#verifies that the hash works
puts lineA
end
end
# trying to put the hash in a csv file
CSV.open("order25.csv", "w") do |csv|
csv << ['name', 'address', 'state', 'pingtime']
splitup.each do |rows|
csv << rows
end
end