Skip to content

unwrap

rel.unwrap([:attr])
rel.unwrap([:attr1, :attr2])

Flatten nested Hash/object attributes into top-level tuple attributes.

Example: I have tuples with nested address hashes, and I want to flatten them into individual columns.

The unwrap operator takes tuples containing Hash/object-valued attributes and flattens them, promoting the nested keys to top-level attributes. This is the inverse of a wrap operation.

Given a tuple like { name: "Alice", address: { city: "London", country: "UK" } }, unwrapping the address attribute produces { name: "Alice", city: "London", country: "UK" }.

Multiple attributes can be unwrapped in a single operation by passing an array of attribute names.

The specified attributes must contain Hash/object values.

wrapped = Bmg::Relation.new([
{ id: 1, name: "Alice", address: { city: "London", country: "UK" } },
{ id: 2, name: "Bob", address: { city: "Paris", country: "France" } },
{ id: 3, name: "Carol", address: { city: "Berlin", country: "Germany" } }
])
wrapped.unwrap([:address]).to_a
=>
[{:id=>1, :name=>"Alice", :city=>"London", :country=>"UK"},
{:id=>2, :name=>"Bob", :city=>"Paris", :country=>"France"},
{:id=>3, :name=>"Carol", :city=>"Berlin", :country=>"Germany"}]

unwrap and ungroup both flatten nested data, but they work differently:

OperatorInputOutput
unwrapHash/object attribute {a: {x: 1, y: 2}}Flat tuple {x: 1, y: 2} (1 tuple out)
ungroupRelation/array attribute {a: [{x: 1}, {x: 2}]}Multiple tuples (N tuples out)
  • Use unwrap for Hash/object attributes (one-to-one flattening)
  • Use ungroup for Relation/array attributes (one-to-many flattening)