These are some Ruby code-golfing tricks I learned from playing Clash of Code(opens new window). These tricks can help when playing the "shortest" mode but excessively using these tricks can lead to less readable code.

#sum accepts a block:

"1 2 3"
"1 2 3".split.sum(&:to_i)

$> is STDOUT:

print 1

$< is STDIN:


[*x] is x.to_a:


Range does not need an ending:


Range has #% to iterate with desired step:

[*(1..10) % 3]

[*(10..1) % -1]

Integer has #digits:

One-character can be presented using ?:



Generate a fixed-size array using a block with{|x|x*x}{|x|x*x}

To check if any of the numbers are 0, multiply them together and check once:


You can assign things to variable without a parens if it’s the rightmost term:

b=3*a=2    # equivalent to b=3*(a=2)

Ruby doesn’t usually coerce strings to numbers (and this can be annoying when codegolfing) but it does coerce string to number when formatting:

"%b" % "1234"

Hashes have to_proc: { |name| things[name] }

Hashes have transform_values: { |k, v| [k, f(v)] }.to_h
hash.transform_values { |v| f v }

Enumerables have grep and grep_v (for inverse):

(1..100).select { |x| (38..44).include? x }
(1..100).select { |x| (38..44) === x }
(1..100).grep 38..44

Numbers (actually, any Comparable) can be clamped:

[[progress, 0].max, 100].min
progress.clamp(0, 100)

Integer#pow can take a modulus:

2.pow(12345678) % 10000   # works, but slow
2.pow(12345678, 10000)    # very fast

2.pow(123456789) % 10000  # => NaN + warning: in a**b, b may be too big
2.pow(123456789, 10000)   # => 6112