Multiple Assignment: Unpack Everything in One Shot
Ruby's multiple assignment lets you pull apart arrays, swap variables, skip fields, and destructure nested data in a single line. If you've been writingmy ($ip, $port) = split(/:/, $line) in Perl, you already get the concept. Ruby just takes it further.
Part 1: Basic Multiple Assignment
# Assign multiple variables at once a, b, c = 1, 2, 3 # Swap without temp variable a, b = b, a # Perl: ($a, $b) = ($b, $a); # Unpack from split ip, port = line.split(":") # Perl: my ($ip, $port) = split(/:/, $line);
Part 2: Skipping Fields with Underscore
Use_ to discard unwanted values:
Perl uses# Skip fields (like /etc/passwd parsing) _, user, _, home = passwd_line.split(":") # Perl: my (undef, $user, undef, $home) = split(/:/, $line); # Skip first element _, *rest = array # Skip return values _, result = method_returning_two_values
undef as a placeholder. Ruby uses _. Shorter, cleaner, same idea.
Part 3: Nested Destructuring
Ruby can unpack nested arrays in one assignment:Perl equivalent: manual unpacking with array refs. Ruby does it automatically in one expression. That's not a small difference when you're parsing structured data.# Nested array unpacking (a, b), c, d = [[1, 2], 3, [4, 5]] # a => 1, b => 2, c => 3, d => [4, 5] # Deep nesting ((a, b), c), d = [[[1, 2], 3], 4] # a => 1, b => 2, c => 3, d => 4
Part 4: Destructuring in Block Parameters
# Hash iteration gives [key, value] pairs hash.each do |key, value| puts "#{key}: #{value}" end # Nested data structures data = [[[1, 2], "info"], [[3, 4], "more"]] data.each do |(coords, label)| x, y = coords puts "#{label}: #{x}, #{y}" end
Part 5: Multiple Return Values
Ruby methods can return multiple values (actually returns an array that auto-unpacks):def get_stats(data) min = data.min max = data.max avg = data.sum / data.size.to_f return min, max, avg # returns [min, max, avg] end minimum, maximum, average = get_stats(numbers) # Perl: my ($min, $max, $avg) = get_stats(@numbers);
Part 6: Practical Examples
Multiple assignment is one of those features that makes Ruby code visually obvious. You see the shape of the data on the left side of the# Parse key=value lines key, value = line.split("=", 2) # Parse Apache log fields ip, _, _, timestamp, request, status, size = line.split(" ", 7) # Unpack CSV with headers header = lines.first.split(",") lines[1..].each do |line| fields = line.split(",") # zip headers with fields record = header.zip(fields).to_h end
= and immediately understand what's being extracted.
Created By: Wildcard Wizard. Copyright 2026