我有一个哈希如下:
random_data = {
0=>{"ABC"=>"201604", "CDE"=>"0002874", "TPP"=>"000004971821467", "APD"=>"00182", "PRODUCTID"=>"ACH", "OPP"=>"00000000000176564", "CTC"=>"00000000000286920"},
1=>{"ABC"=>"301604", "CDE"=>"0001074", "TPP"=>"000004971821467", "APD"=>"00182", "PRODUCTID"=>"ACH", "OPP"=>"00000000000119964", "CTC"=>"00000000000211920"}
}
和2个数组如下:
arr1 = [CHAR,NUMBER,NUMBER,NUMBER,CHAR,NUMBER,CHAR]
arr2 = [6,(7,0),(15,0),(5,0),3,(15,2),17]
arr1和arr2的元素用哈希值映射,条件如下:
arr1
的元素是char,则不对哈希值执行任何操作。arr1
的元素为NUMBER,则散列random_data
中的对应元素应转换为整数,即应删除前导零。例如,arr1 [1]是'Number',因此对于hash的每个第二个元素,应该删除前导零。
即。 “CDE”=>“0002874”应成为“CDE”=>“2874”
arr1
为NUMBER且arr2
元素的第二个数字不为0,则应在哈希中添加小数。
举个例子:
arr1 [5] =数字
arr2 [5] =(15,2)然后哈希OPP
中的第5个元素应该变成这样的“OPP”=>“1199.64”,即为2个位置添加小数(15,2)
预计产出如下:
random_data = {
0=>{"ABC"=>"201604", "CDE"=>"2874", "TPP"=>"4971821467", "APD"=>"182", "PRODUCTID"=>"ACH", "OPP"=>"1765.64", "CTC"=>"00000000000286920"},
1=>{"ABC"=>"301604", "CDE"=>"1074", "TPP"=>"4971821467", "APD"=>"182", "PRODUCTID"=>"ACH", "OPP"=>"1199.64", "CTC"=>"00000000000211920"}
}
答案 0 :(得分:1)
arr1 = %w| CHAR NUMBER NUMBER NUMBER CHAR NUMBER CHAR |
#=> ["CHAR", "NUMBER", "NUMBER", "NUMBER", "CHAR", "NUMBER", "CHAR"]
arr2 = [6, [7,0], [15,0], [5,0], 3, [15,2], 17]
enum = arr1.zip(arr2).map { |type, obj| type=="CHAR" ? type : obj.last }.to_enum
#=> #<Enumerator: ["CHAR", 0, 0, 0, "CHAR", 2, "CHAR"]:each>
random_data.each do |k,h|
h.update(h) do |*,v|
obj = enum.next
case obj
when "CHAR"
v
else
x = v.to_i
x = x.to_f/10**obj if obj > 0
x.to_s
end
end
enum.rewind
end
#=> {0=>{"ABC"=>"201604", "CDE"=>"2874", "TPP"=>"4971821467", "APD"=>"182",
# "PRODUCTID"=>"ACH", "OPP"=>"0.17", "CTC"=>"00000000000286920"},
# 1=>{"ABC"=>"301604", "CDE"=>"1074", "TPP"=>"4971821467", "APD"=>"182",
# "PRODUCTID"=>"ACH", "OPP"=>"1199.64", "CTC"=>"00000000000211920"}}
答案 1 :(得分:0)
arr1 = %w|CHAR NUMBER NUMBER NUMBER CHAR NUMBER CHAR|
arr2 = [6, [7,0], [15,0], [5,0], 3, [15,2], 17]
types = arr1.zip(arr2)
random_data.map do |_, hash|
hash.map.with_index do |(k, v), idx|
type, digits = types[idx]
[
k,
type == 'NUMBER' ? v.to_i.to_s.tap do |s|
s[/(?=.{#{[*digits][1]}}\z)/] = '.' unless [*digits][1].zero?
end : v
]
end
end