raw cheat sheet

Ruby Code Golf

Robert Eisele

Variables

Choose one letter variable names

long_variable = "Foo Bar"

v="Foo Bar" # better

Use multiple variable assignments

a = 1
b = 2
c = 3

a,b,c=1,2,3 # better

Use variables in puts

a = "value"
puts "This is a #{value}"

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

Strings

String repetition

100.times do
  print "Foo"
end

print "Foo"*100 # better

Use of single characters

puts "X"

puts ?X # better

Characters from ASCII codes

puts 65.chr

putc 65 # better

shortcut

puts "\n"

puts $/ # better

Regular expressions

String match

if str.match /[a-z]/
  puts "Yep"
end

if str=~/[a-z]/ # better
  puts "Yep"
end

Arrays

Array assignment

x = ["this", "is", "a", "test"]

x=%w(this is a test) # better

Array join

puts arr.join(",")

puts arr*?, # better

Try to set the array as $*

x = []

10.times do |i|
  a << i
end

10.times do |i|
  $* << i # better
end

Alternative to compact

x=[1, nil, 2, nil, nil, 3]
x.compact

x-[nil] # better

Alternative to uniq

a.uniq

a|[] # better

Ranges

Item is member of a range

(0..10).member?(3)

(0..10)===3 # better

Convert range to array

("a".."z").to_a

[*?a..?z] # better

Integers

Use number shortcuts

a = 100000

a=1e5 # better

Print numbers using p

puts 123

p 123 # better

Increment and decrement numbers

a=4
b=5

(a - 1) * 9
(a + 1) * 9

~-a*9 # better
-~a*9 # better

Conditions

Condition shortcut

if w
  puts "Yep"
end

puts "Yep" if w # better

w&&puts "Yep" # best

Others

Shortcut for print

print "bar"

$><<"bar" # better

Remove do end block

20.times do |i|
 puts i
end

20.times{|i|puts i} # better

The result of the last gets is in $_

x=gets
puts x

gets
puts $_ # better

Methods

def f n
  return n + n
end

f=->n{n+n} # better

Write a string multiple times

12.times do
 puts "Hello world"
end

puts ["Hello world"]*12 # better