我有两个需要组合成哈希的数组。但是,其中一个数组永远是关键。因此,我需要查看名称,数字,地址等列表,并为其提供所有标题。一个例子是:
Adjustor name => Chase, Firm name => Chase Bank
然后重复另一个位置。
Adjustor name => Rob, Firm name => Walmart.
以下是我目前的情况:
Array_headers = ['Adjuster Name','Firm Name', 'Firm Number', 'Adjustment Type', 'Address 1', 'Address 2', 'City', 'State', 'Zip Code', 'Phone', 'Fax', 'Website', 'Comments', 'Latitude', 'Longitude', 'Manual LongLatCalc', 'LongLat Error']
Data_examples = ["AdjusterName", "FirmName", "FirmNumber", "AdjustmentType", "Address1", "Address2", "City", "State", "ZipCode", "Phone", "Fax", "WebSite", "Comments", "Latitude", "Longitude", "ManualLongLatCalc", "LongLatError", "chase", "chase bank", "260-239-1761", "property", "501 w", "200 s", "albion", "in", "46701", "555-555-5555", "c@gamil", "whatsupwhatups.com", "hahahah", "12.332", "12.222", "no", "none"]
CombiningArrays= Hash[Array_headers.zip data_examples]
p CombiningArrays
应返回以下内容:
{"Adjuster Name"=>"AdjusterName", "Firm Name"=>"FirmName", "Firm Number"=>"FirmNumber", "Adjustment Type"=>"AdjustmentType", "Address 1"=>"Address1", "Address 2"=>"Address2", "City"=>"City", "State"=>"State", "Zip Code"=>"ZipCode", "Phone"=>"Phone", "Fax"=>"Fax", "Website"=>"WebSite", "Comments"=>"Comments", "Latitude"=>"Latitude", "Longitude"=>"Longitude", "Manual LongLatCalc"=>"ManualLongLatCalc", "LongLat Error"=>"LongLatError", *"Adjuster Name"=>" \r\nchase", "Firm Name"=>"chase", "Firm Number"=>"260-239-1761", "Adjustment Type"=>"property", "Address 1"=>"501 w", "Address 2"=>"200 s", "City"=>"albion", "State"=>"in", "Zip Code"=>"46701", "Phone"=>"555-555-5555", "Fax"=>"c@gamil", "Website"=>"whatsupwhatups.com", "Comments"=>"hahahah", "Latitude"=>"12.332", "Longitude"=>"12.222", "Manual LongLatCalc"=>"no", "LongLat Error"=>"none"*}
它停在"LongLat Error"=>"LongLatError"
,并且所有斜体都没有出现。如何让它不断循环我的其他数组?
我还尝试了以下代码:
#Creating一个方法来浏览数组
def array_hash_converter headers, data
hash = Hash.new
headers.each_with_index do |header, index|
hash[header] = data[index]
end
puts hash
end
i=0
while i < data.count do
array_hash_converter Array_header, data
i+=1
end
请帮助!
答案 0 :(得分:3)
我建议在keys数组长度上对values数组进行切片,然后将它们映射到一个哈希数组中。例如:
sliced_values = Data_examples.each_slice(Array_headers.length)
result = sliced_values.map { |slice| Array_headers.zip(slice).to_h }
您将永远不会得到一个哈希作为结果,因为您将在键上发生冲突,然后,只会返回最后一个结果,因为它会覆盖以前的结果。请记住,散列键在Ruby中是唯一的。
答案 1 :(得分:1)
看起来你真的想要一个哈希数组。所以,你的第一个数组将成为哈希键的列表(我将其称为“HEADER_KEYS”)。在你的第二个数组中,我看到“\ r \ n”。您可能需要备份一个步骤。我假设这是来自CSV,所以有已知的分隔符和未知的行数。要开始解析您的CSV,请拆分“\ r \ n”(或任何换行符),然后迭代这些项目并在逗号上拆分。就像是:
final_dataset = []
HEADER_KEYS = [].freeze # put your actual array_of_headers here and freeze it
array_of_rows = []
csv_string.split("\r\n").each { |row| array_of_rows.push(row.split) }
这应该为您提供一个可以循环的数组。
array_of_rows.each do |row|
row_hash = {}
HEADER_KEYS.each_with_index do |key, index|
row_hash[key] = row[index]
end
final_dataset.push(row_hash)
end
可能有一种更优雅的方式来处理这个问题,但这应该可以帮助您实现目标。