Instructions
Create a function index_by_id that takes an array of hashes
(each with an :id key) and returns a hash indexed by id.
Use each_with_object to build a hash:
```ruby
[1, 2].each_with_object({}) { |n, hash| hash[n] = n * 2 }
=> {1 => 2, 2 => 4}
Example:
```ruby
users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
]
index_by_id(users)
# => { 1 => { id: 1, name: "Alice" }, 2 => { id: 2, name: "Bob" } }
Hints:
- Use each_with_object({}) { |item, hash| ... }
- Set hash[item[:id]] = item
- The result is built incrementally
Your Code
def index_by_id(items)
items.each_with_object({}) { |item, hash| hash[item[:id]] = item }
end
RSpec.describe "index_by_id" do
it "indexes by id" do
users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
]
result = index_by_id(users)
expect(result[1]).to eq({ id: 1, name: "Alice" })
expect(result[2]).to eq({ id: 2, name: "Bob" })
end
it "handles empty array" do
expect(index_by_id([])).to eq({})
end
end
Results
Click "Run Tests" to see results