raw Software
RAW Software Programming Languages Ruby

Ruby Code Golf Cheat Sheet

Robert Eisele

Ruby Code Golf Cheat Sheet: compact syntax, implicit variables, command-line switches, and standard-library behavior that reduce byte counts in programming puzzles. Golfed Ruby deliberately trades readability and robustness for size, so verify every entry against the Ruby version and input contract used by the challenge.

Measure Before Golfing

Count source bytes; code-golf scores usually count bytes, not characters

ruby -e 'p File.binread(ARGV[0]).bytesize' solution.rb

Check syntax without running the program

ruby -wc solution.rb

Parser details change across Ruby releases. A submission is valid only for the interpreter version declared by the challenge.

Variables and Assignment

Use one-letter local names when a value must be reused

long_variable="Foo Bar"
v="Foo Bar"

Assign several values at once

a,b,c=1,2,3

Swap values without a temporary variable

a,b=b,a

Assign only when the current value is false or nil

a||=default

Interpolate a global variable without braces

$a="value"
puts "This is #$a"

Strings and Output

Repeat a string

$><<"Foo"*100

Write without the newline added by puts

$><<"text"

Print an inspected value with a newline

p value

Use a one-character string literal

?X

Print a character from its integer code

putc 65

Use the current input record separator, normally a newline

$/

Interpolate an expression instead of concatenating converted values

"#{a}:#{b}"

Input and Implicit Globals

Read one line; gets also stores it in $_

gets
puts $_

Read all remaining input as one string

$<.read

Iterate over every input line from files or standard input

$<.map{_1.to_i}

Access command-line arguments through Ruby's shorter alias

$*

$* is ARGV. Reusing it as scratch storage is valid only when the original arguments are no longer needed.

Arrays

Create an array of whitespace-separated words

%w[this is a test]

Create an array of symbols

%i[red green blue]

Join with a one-character separator using Array#*

puts a*?,

Repeat an array; puts emits each element on its own line

puts ["Hello world"]*12

Remove nil values by array difference

a-[nil]

Remove duplicates while preserving first occurrence order

a|[]

Flatten one level with splat construction

[*a,*b]

Take the first and last element

a[0]
a[-1]

Enumerables and Blocks

Use numbered block parameters when supported by the target Ruby

a.map{_1*2}

Map with an existing method

a.map(&:to_i)

Count truthy matches without selecting first

a.count{_1>0}

Sum mapped values directly

a.sum{_1*_1}

Use braces instead of a multiline do/end block

20.times{|i|puts i}

Numbered parameters were introduced in Ruby 2.7. For older interpreters, use an explicit block parameter such as {|x|x*2}.

Ranges and Hashes

Test range membership with case equality

(0..10)===3

Expand a character range into an array

[*?a..?z]

Use an exclusive range when the upper bound must be omitted

0...n

Create a frequency table

a.tally

Create a counting hash on older Ruby versions

h=Hash.new 0
a.map{h[_1]+=1}

Enumerable#tally was introduced in Ruby 2.7.

Numbers and Operators

Increment or decrement an integer through bitwise complement

-~n # n+1
~-n # n-1

Test odd or even through the low bit

n&1

Convert a Boolean condition to zero or one

condition ? 1:0

Use exponent notation only when a Float is acceptable

1e5 # 100000.0, not an Integer

Unary operators can save bytes but are easy to misread. Parenthesize when neighboring operators would change parsing.

Conditions and Control Flow

Use a statement modifier for a one-line condition

puts "Yep" if w

Use short-circuit evaluation when the left side is genuinely Boolean

w&&puts("Yep")

Select one of two expressions

w ? yes:no

Loop while an expression remains truthy

work while condition

In Ruby, only false and nil are falsey. In particular, 0 and empty strings are truthy.

Regular Expressions

Test whether a string matches

s=~/[a-z]/

Replace all matches

s.gsub(/\d/,?X)

Scan all matching substrings

s.scan(/\w+/)

=~ returns the match offset or nil, not a Boolean. That is ideal in conditions but can matter when the value itself is used.

Functions

Omit parentheses and an explicit return in a method

def f(n)=n+n

Use a lambda when assigning the callable is shorter

f=->n{n+n}
f[3]

Endless method definitions require Ruby 3.0 or newer. The compact lambda form works on older modern Ruby versions.

Ruby as a Command-Line Filter

Run code once for every input line; the current line is $_

ruby -ne '...' input

Run code for every line and print $_ afterward

ruby -pe '...' input

Autosplit each line into $F, normally on whitespace

ruby -ane 'p $F' input

Choose the autosplit delimiter with -F

ruby -F, -ane 'p $F' input.csv

Chomp each input record and add the output record separator back on print

ruby -lpe '...' input

Interpreter flags are often counted as part of a golf submission. Check the challenge's scoring convention before relying on them.