Step 1: Compare how easily magnesium and iron give up electrons.
Magnesium sits well above iron in the reactivity series, meaning it loses electrons and gets oxidised far more readily than iron does. This gap in reactivity is exactly what gets exploited here.
Step 2: Let magnesium take the hit instead of iron.
When a magnesium block is connected to the iron pipeline, a small electrochemical cell effectively forms between them, with magnesium acting as the anode. Since magnesium oxidises far more readily, $Mg \rightarrow Mg^{2+} + 2e^-$, it keeps donating its own electrons instead of letting iron lose any.
Step 3: See how those electrons protect the iron.
The electrons released by magnesium flow into the iron pipe, forcing the iron to behave as the cathode instead of the anode. Since oxidation, and therefore rusting, only happens at an anode, the iron pipe is spared as long as the magnesium keeps supplying electrons.
Step 4: Name the method.
Because magnesium is deliberately allowed to corrode in place of the iron, this technique is called cathodic protection using a sacrificial anode, and the magnesium blocks need periodic replacement once they are used up.
\[ \boxed{\text{Magnesium acts as a sacrificial anode, protecting the iron pipeline by cathodic protection}} \]