0

I have the arrays months and monthly_doc_count_for_topic.

  months = ["2019-01-01", "2019-02-01", "2019-03-01", "2019-04-01"]
  monthly_doc_count_for_topic =  [
    ["foo","2019-02-01: 186904","2019-03-01: 196961"],
    ["bar","2019-01-01: 8876","2019-04-01: 8694"]
  ]
  goal = [ 
    ["foo","2019-02-01: 186904","2019-03-01: 196961","2019-01-01","2019-02-01","2019-03-01","2019-04-01"],
    ["bar","2019-01-01: 8876","2019-04-01: 8694","2019-01-01","2019-02-01","2019-03-01","2019-04-01"]
  ]

I'd like to fill in element of the array months into arrays inside monthly_doc_count_for_topic so it looks like array goal.

My attempt:

  monthly_doc_count_for_topic.map do |topic_set| 
    months.each { |month| topic_set << month }
  end

But I'm getting:

=> [
  [0] [
    [0] "2019-01-01",
    [1] "2019-02-01",
    [2] "2019-03-01",
    [3] "2019-04-01"
  ],
  [1] [
    [0] "2019-01-01",
    [1] "2019-02-01",
    [2] "2019-03-01",
    [3] "2019-04-01"
  ]
] 

it's not appending the values from monthly_doc_count_for_topic instead replacing it with elements from array months. How can I modify my code to achieve the output like array goal? Thank you very much!

3
  • It appears you want monthly_doc_count_for_topic.map { |topic_set| topic_set + months }. Commented Jan 9, 2020 at 9:41
  • @CarySwoveland but this triples the elements of months into the nested sets Commented Jan 9, 2020 at 9:43
  • Oh, I was wrong! Your code works perfectly fine! @CarySwoveland Can you post this as an answer so that I can accept it as solution? Thank you very much!!! Commented Jan 9, 2020 at 9:52

1 Answer 1

1

In your attempt replace

monthly_doc_count_for_topic.map

with

monthly_doc_count_for_topic.each

and it works perfectly fine:

goal = monthly_doc_count_for_topic.each do |topic_set|
  months.each { |month| topic_set << month }
end

But I'd prefer CarySwoveland's solution in the comment, it's less verbose:

monthly_doc_count_for_topic.map { |topic_set| topic_set + months }

Sign up to request clarification or add additional context in comments.

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.