Outer_join.rb
This content was produced by an LLM and could include errors.
This script merges user data with corresponding post data. It iterates through all users, finds matching posts by ID, and adds the post’s title to each user record, ensuring completeness.
users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
]
#=> [{id: 1, name: "Alice"}, {id: 2, name: "Bob"}, {id: 3, name: "Charlie"}]
posts = [
{ id: 1, user_id: 1, title: 'Post 1' },
{ id: 2, user_id: 2, title: 'Post 2' }
]
#=> [{id: 1, user_id: 1, title: "Post 1"}, {id: 2, user_id: 2, title: "Post 2"}]
users.map do |user|
post = posts.find { |p| p[:user_id] == user[:id] }
user.merge(post || { title: nil })
end
#=> [{id: 1, name: "Alice", user_id: 1, title: "Post 1"},
{id: 2, name: "Bob", user_id: 2, title: "Post 2"},
{id: 3, name: "Charlie", title: nil}]
Ruby 4.0.3