gpt4 book ai didi

ruby - 在 Ruby 中将数组元素(字符串)设置为变量名

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:14 25 4
gpt4 key购买 nike

我有以下数组,稍后我用它来在 Excel 文件上写入标题。

fields = ["fileName", "type", "id"]

然后我有以下从 XML 中读取值的代码:

filename = xml.xpath('//path/filename').text
type = xml.xpath('//path/type').text
id = xml.xpath('//path/id').text

我迭代初始数组(字段)以便将 Excel 单元格设置为在上一步中提取的值:

row = 2
c = 1
fields.each do |content|
ws.Cells(row,c).Value = content
c = c + 1

我正在尝试将数组的(字段)内容作为变量名而不是字符串,以便能够重用头部字段。

谁能推荐一种实现它的方法?

最佳答案

这听起来像是您需要使用 Hash将字段名称与您提取的值相关联:

fields = {
"fileName" => xml.xpath('//path/filename').text,
"type" => xml.xpath('//path/type').text,
"id" => xml.xpath('//path/id').text
}

row=2
c=1
fields.each do |key,value|
ws.Cells(row,c).Value = value
c=c+1
end

关于ruby - 在 Ruby 中将数组元素(字符串)设置为变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10604759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com