Ruby golf

Ruby is full of tricks for golfing. You probably don’t want to use these in production code (for that, see Ruby idioms).

Examples

Simple values

Use p instead of nil.1

Use ? to make a 1-character string literal:

c="A"  # old
c=?A   # new

Use symbols instead of string literals if a string is not required:

s='foo'  # old
s=:foo   # new

# This works for both:
"#{s}bar"

# This only works for strings:
s+'bar'

Arrays

Use * to join an array:

a.join      # old
a*''        # new

a.join ','  # old
a*?,        # new

Use | or & to remove duplicates from an array:

s.chars.uniq  # old
s.chars|[]    # new

a.uniq        # old
a&a           # new

To remove nil values from an array, subtract an array containing nil:

a.compact  # old
a-[p]      # new

Functions

Lambdas can be shorter than functions:

def f x;do_something(x);end;f n  # old
f=->x{do_something(x)};f[x]      # new
  1. The built-in method p returns nil when called without arguments.