传输到哈希值的数据数组并将键导出到输出文件



我有以下测试数据,需要通过 ruby 编程导出为我所需的输出中显示的格式。实际数据数组有 1000000 条记录。

data_array1=aaaa
data_array2=bbbb
----------------
----------------
data_array8=hhhh , which means there are 8 data array, those have the following format :
aaaa= [a,[1,2,3,4],20]
bbbb= [b,[8,7,9,19],23]
-----------------------
-----------------------
hhhh= [h,[25,26,29,30],28]

我想要的输出需要导出到文本文件(仅供参考的标头,无需包含在输出文件中(:

输出.txt

哈希 TX 时间

a    1    20
a    2    20
a    3    20
a    4    20
b    8    25
b    7    25
b    9    25
b    19   25
------------
------------
h    25   28
h    26   28
h    29   28
h    30   28

我是 Ruby 的新手,到目前为止我已经这样做了,但尚无定论:

def bhash
1.upto(8) do |bid|
blk=[bid]
keys = %w[hash tx time ]
data = keys.map{|key| blk[key]}
hash, txids, time, difficulty = data
CSV.open('output.txt', 'w', headers: keys, write_headers: true, col_sep: 
"t") do |csv|
txids.each do |tx|
csv << [hash,tx,time]
end
end
end 

提前感谢您的所有帮助。

给定一个包含以下内容的文件json.txt

["a",[1,2,3,4],20]
["b",[8,7,9,19],23]
["h",[25,26,29,30],28]

以下程序:

require 'csv'
require 'pp'
require 'json'
def custom_expansion(a)
expanded = Array.new
h = Hash.new
h['hash'] = a[0]
h['time'] = a[2]
inside = a[1]
inside.each do |tx|
h['tx'] = tx
expanded.push h.dup
end
expanded
end
CSV.open('output.txt', 'w', col_sep: "t") do |csv|
File.open('json.txt') do |f|
while !f.eof?
array = JSON.parse(f.readline)
ex = custom_expansion(array)
ex.each do |e|
csv << [ e['hash'], e['tx'], e['time'] ]
end
end
end
end

将在output.txt中产生这个:

a   1   20
a   2   20
a   3   20
a   4   20
b   8   23
b   7   23
b   9   23
b   19  23
h   25  28
h   26  28
h   29  28
h   30  28

最新更新