Cameron Cameron - 2 months ago 8
Ruby Question

Create new array of arrays from key

I have an array:

[{
"name": "Category 1",
"entries": [{
"question": "Question 1",
"answer": "Answer 1"
}, {
"question": "Question 2",
"answer": "Answer 2"
}, {
"question": "Question 3",
"answer": "Answer 3"
}]
}, {
"name": "Category 2",
"entries": [{
"question": "Question 1",
"answer": "Answer 1"
}, {
"question": "Question 2",
"answer": "Answer 2"
}, {
"question": "Question 3",
"answer": "Answer 3"
}]
}]


What I want to do is create a new array of just the entries.

So I end up with this:

[{
"question": "Question 1",
"answer": "Answer 1"
}, {
"question": "Question 2",
"answer": "Answer 2"
}, {
"question": "Question 3",
"answer": "Answer 3"
}, {
"question": "Question 1",
"answer": "Answer 1"
}, {
"question": "Question 2",
"answer": "Answer 2"
}, {
"question": "Question 3",
"answer": "Answer 3"
}]


In PHP I would of just do a push into a new array... but in Ruby is it possible to use
group_by
or
collect
to achieve this?

Answer

Use Enumerable#flat_map:

array = [{
    "name": "Category 1",
    "entries": [{
        "question": "Question 1",
        "answer": "Answer 1"
    }, {
        "question": "Question 2",
        "answer": "Answer 2"
    }, {
        "question": "Question 3",
        "answer": "Answer 3"
    }]
}, {
    "name": "Category 2",
    "entries": [{
        "question": "Question 1",
        "answer": "Answer 1"
    }, {
        "question": "Question 2",
        "answer": "Answer 2"
    }, {
        "question": "Question 3",
        "answer": "Answer 3"
    }]
}]
array.flat_map { |hash| hash[:entries] }
   #=> [{:question=>"Question 1", :answer=>"Answer 1"},
   #  {:question=>"Question 2", :answer=>"Answer 2"},
   #  {:question=>"Question 3", :answer=>"Answer 3"},
   #  {:question=>"Question 1", :answer=>"Answer 1"},
   #  {:question=>"Question 2", :answer=>"Answer 2"},
   #  {:question=>"Question 3", :answer=>"Answer 3"}]
Comments