Ruby Quick Reference

Quick reference for efficient coding

View the Project on GitHub YumaYX/RubyQuickReference

outer_join.rb(join)

Execution:

users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
]
#=> [{:id=>1, :name=>"Alice"}, {:id=>2, :name=>"Bob"}, {:id=>3, :name=>"Char...

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"},


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

Executed with Ruby 3.3.5