Cameron - 1 year ago 81

Ruby Question

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`

`collect`

Answer Source

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"}]
```