Ruby:使用子数组中的值创建字符串

时间:2014-05-27 16:01:49

标签: ruby

我有多维数组,我试图创建一个字符串,根据位置访问每个子数组的值。例如:

appointments = [["get lunch", "3pm", "fancy clothes"], ["walk the dog", "1pm", "sweat pants"]]

我想通过迭代每个子数组并以下列格式输出值来使用此信息创建单个字符串:

"You have an appointment to #{subarray[0]} at #{subarray[1]}.
Make sure you wear #{subarray[2]}."

因此,最终输出将是:

"You have an appointment to get lunch at 3pm.
Make sure you wear fancy clothes.

You have an appointment to walk the dog at 1pm.
Make sure you wear sweat pants."

关于如何实现这一目标的任何建议?

2 个答案:

答案 0 :(得分:4)

根据您的格式非常简单:

appointments = [["get lunch", "3pm", "fancy clothes"], ["walk the dog", "1pm", "sweat pants"]]

appointments.collect do |subarray|
  "You have an appointment to #{subarray[0]} at #{subarray[1]}.\nMake sure you wear #{subarray[2]}.\n"
end.join("\n")

如果您利用自然顺序,这会更容易:

appointments.collect do |subarray|
  "You have an appointment to %s at %s.\nMake sure you wear %s.\n" % subarray
end.join("\n")

答案 1 :(得分:3)

appointments.map do |subarray|
  "You have an appointment to #{subarray[0]} at #{subarray[1]}.\nMake sure you wear #{subarray[2]}."
end.join("\n\n")
# => "You have an appointment to get lunch at 3pm.\nMake sure you wear fancy clothes.\n\nYou have an appointment to walk the dog at 1pm.\nMake sure you wear sweat pants."

您还可以将变量命名为:

appointments.map do |appointment, time, clothing|
  "You have an appointment to #{appointment} at #{time}.\nMake sure you wear #{clothing}."
end.join("\n\n")