Ruby noob在这里。我在ruby脚本中有多个数组,我想追加创建一个带有键值对的字符串,其中id数组的每个值都匹配id_desc数组的等效值,如下所示:
ids = [1234, 2345, 3456]
ids_desc = ["inst1", "inst2", "inst3"]
如何完全按照上述数组中的说明构建以下字符串:
"The key for id '#{id}' has a value of '#{id_desc}'"
应输出:
"The key for id '1234' has a value of 'inst1'"
"The key for id '2345' has a value of 'inst2'"
etc.
我可以很容易地做到以下几点:
str1 = Array.new
ids.each do |id|
str1 << "The key for id '#{id}'"
end
但是,我无法确定如何在每个键映射的末尾添加“具有#{id_desc}值”。有人有什么建议吗?
谢谢!
答案 0 :(得分:1)
如果ids
和ids
长度相同,您可以压缩ids_desc
数组:
ids.zip(ids_desc).each do |id, desc|
str1 << "The key for id #{id} has a value of #{desc}"
end
或者只使用Enumerable#each_with_index
:
ids.each_with_index do |id, i|
str1 << "The key for id #{id} has a value of #{ids_desc[i]}"
end
您可以使用str1
Array#map
数组
ids.zip(ids_desc).map do |id, desc|
"The key for id #{id} has a value of #{desc}"
end
答案 1 :(得分:0)
ids = [1234, 2345, 3456]
ids_desc = ["inst1", "inst2", "inst3"]
array = ids.zip(ids_desc).map { |e| "The key for id '%d' has a value of '%s'" % e }
array.map { |e| puts e }
id&#39; 1234&#39;的关键的值为&#39; inst1&#39;
id&#23; 2345&#39;的值为&#39; inst2&#39;
id&#39; 3456&#39;的关键值为&#39; inst3&#39;