Trailing Conditionals: Put the Important Stuff First
Just like Perl, Ruby lets you put conditions at the end of a statement. The action comes first, the condition comes second. It reads like English and saves you from writing three lines when one will do. If you already writeprint if /ERROR/ in Perl, you're going to feel right at home.
Part 1: Postfix if and unless
# Postfix if puts line if line =~ %r~error~i # Perl: print $line if $line =~ /error/i; # Postfix unless puts line unless line.empty? # Perl: print $line unless $line eq ''; # With method calls next unless line.include?("WARNING") # skip iteration exit 1 if errors.any? # bail out retry if attempts < 3 # retry block
Part 2: unless vs if !
unless is Ruby's (and Perl's) negative conditional. Reads more naturally than if !:
Rule of thumb: if you need# These are equivalent: puts "missing" unless File.exist?(path) puts "missing" if !File.exist?(path) # unless reads better for simple negation # Avoid unless with complex conditions though: # BAD: do_thing unless !ready? && !paused? (confusing) # GOOD: do_thing if ready? || paused?
unless with && or ||, you've gone too far. Switch to if and flip the logic.
Part 3: Ternary Operator
Same as Perl and C:status = count > 0 ? "found" : "none" label = valid? ? "OK" : "FAIL" # In interpolation: puts "Status: #{count > 0 ? 'found' : 'none'}" # Perl: my $status = $count > 0 ? "found" : "none";
Part 4: Postfix while and until
# Rarely used but available line = gets until line =~ %r~\S~ # skip blank lines attempts += 1 while retrying?
Part 5: Practical One-Liners
Trailing conditionals are the single best feature for one-liners. The action is what you see first, the condition is the fine print. Perfect for scanning code and knowing immediately what it does.# Print non-empty, non-comment lines ruby -ne 'puts $_ unless $_ =~ %r~^\s*(#|$)~' # Number only matching lines ruby -ne 'printf "%d: %s", $., $_ if /ERROR/' # Skip header line ruby -ne 'puts $_ unless $. == 1' data.csv
Created By: Wildcard Wizard. Copyright 2026