1

I have a date, stored as a string.

date_added = "2019-12-28T20:32:27Z"

I need to add that to every item in an array.

tracks = ["6tIlpznHyaqCPiVfolKxrV", "5sKHRsDybtkw6lxufkyk08", "0ZWBuv544C0STkXfYb9Sd5"]

So, the final output should be:

[["6tIlpznHyaqCPiVfolKxrV", "2019-12-28T20:32:27Z"], ["5sKHRsDybtkw6lxufkyk08", "2019-12-28T20:32:27Z"], ["0ZWBuv544C0STkXfYb9Sd5", "2019-12-28T20:32:27Z"]]

How can add that date item to every item in an array? I've looked into zip and push but wasn't able to get that desired outcome.

1

2 Answers 2

7

The tracks array contains strings whereas the final output contains others arrays. Those are different classes and since you can't change the class of an object, "adding" to the existing items doesn't really work. You have to create new elements (arrays) which are composed of one of the old elements (a string) and the date_added (another string).

You could use product and let Ruby combine tracks with [date_added]:

tracks.product([date_added])
#=> [["6tIlpznHyaqCPiVfolKxrV", "2019-12-28T20:32:27Z"],
#    ["5sKHRsDybtkw6lxufkyk08", "2019-12-28T20:32:27Z"],
#    ["0ZWBuv544C0STkXfYb9Sd5", "2019-12-28T20:32:27Z"]]

or use map to create the sub-arrays:

tracks.map { |t| [t, date_added] }
#=> [["6tIlpznHyaqCPiVfolKxrV", "2019-12-28T20:32:27Z"],
#    ["5sKHRsDybtkw6lxufkyk08", "2019-12-28T20:32:27Z"],
#    ["0ZWBuv544C0STkXfYb9Sd5", "2019-12-28T20:32:27Z"]]
Sign up to request clarification or add additional context in comments.

Comments

1

Just for the record:

date_added = "2019-12-28T20:32:27Z"
racks = ["6tIlpznHyaqCPiVfolKxrV", "5sKHRsDybtkw6lxufkyk08", "0ZWBuv544C0STkXfYb9Sd5"]

racks.zip([date_added] * racks.size) 
# => [["6tIlpznHyaqCPiVfolKxrV", "2019-12-28T20:32:27Z"],
#     ["5sKHRsDybtkw6lxufkyk08", "2019-12-28T20:32:27Z"],
#     ["0ZWBuv544C0STkXfYb9Sd5", "2019-12-28T20:32:27Z"]]

But, if at all possible, I wouldn't massage the array resulting in expanding its size with redundant information as zip or product would do. Instead, I'd massage each element as they're being accessed to tack on the date, something like:

racks.each do |r|
  foo([r, date_added])
end

The end result would be what @Stefan suggested using map as long as you didn't store the map result in an intermediate value.

2 Comments

Depending on preference racks.zip([date_added] * racks.size) could be replaced with racks.zip([date_added].cycle).
Cool! I never thought about using cycle like that.

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.