Instructions
Create a function all_tags that takes an array of posts (hashes)
and returns a flat array of all unique tags.
Each post has a :tags key with an array of strings.
Use flat_map to collect all tags, then uniq to remove duplicates:
```ruby
[[1, 2], [3, 4]].flat_map { |arr| arr }
=> [1, 2, 3, 4]
Example:
```ruby
posts = [
{ title: "Ruby", tags: ["ruby", "programming"] },
{ title: "Rails", tags: ["ruby", "rails"] }
]
all_tags(posts) # => ["ruby", "programming", "rails"]
Hints:
- Use .flat_map { |post| post[:tags] }
- flat_map = map + flatten(1)
- Add .uniq to remove duplicates
Your Code
def all_tags(posts)
posts.flat_map { |post| post[:tags] }.uniq
end
RSpec.describe "all_tags" do
it "collects unique tags" do
posts = [
{ title: "Ruby", tags: ["ruby", "programming"] },
{ title: "Rails", tags: ["ruby", "rails"] }
]
expect(all_tags(posts)).to contain_exactly("ruby", "programming", "rails")
end
it "handles empty posts" do
expect(all_tags([])).to eq([])
end
it "handles posts with empty tags" do
posts = [{ title: "No tags", tags: [] }]
expect(all_tags(posts)).to eq([])
end
end
Results
Click "Run Tests" to see results