Ruby golf

Ruby is full of code golf tricks. You probably don’t want to use these in production code.

Examples

Basic values

Use p instead of nil.1

x=nil  # old
x=p    # new (-2)

Use ? to make a 1-character string literal:

c="A"  # old
c=?A   # new (-1)

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

s='foo'  # old
s=:foo   # new (-1)

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

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

Arrays

Use * to join an array:

a.join      # old
a*''        # new (-2)

a.join ','  # old
a*?,        # new (-6)

Use | or & to remove duplicates from an array:

s.chars.uniq  # old
s.chars|[]    # new (-2)

a.uniq        # old
a&a           # new (-3)

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

a.compact  # old
a-[p]      # new (-4)

Blocks and functions

Lambda procs can be shorter than functions:

def f x;do_something(x);end;f n  # old
f=->x{do_something(x)};f[x]      # new (-4)

Ruby 2.7+ supports numbered parameters in blocks:

h.map{|k,v|do_something(k,v)}  # old
h.map{do_something(_1,_2)}     # new (-3)
  1. The built-in method p returns nil when called without arguments.