0

I have multidimensional array and I'm trying to create a string that accesses the values of each subarray based on position. For example:

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

I want to use this information to create a single string by iterating over each subarray and outputting the values in the following format:

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

Therefore, the final output would be something like:

"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."

Any suggestions on how can I accomplish this?

2 Answers 2

4

Pretty simple given your format:

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")

This is even easier if you take advantage of the natural ordering:

appointments.collect do |subarray|
  "You have an appointment to %s at %s.\nMake sure you wear %s.\n" % subarray
end.join("\n")
Sign up to request clarification or add additional context in comments.

Comments

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."

You could also make your variables named:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.