Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

What general tips do you have for golfing in Ruby? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Ruby (e.g. "remove comments" is not an answer). Please post one tip per answer.

-- borrowed from marcog's idea ;)

share|improve this question
The answers are community wiki, so I edited some. –  kernigh May 24 '14 at 16:22
I don't think accepting an answer makes sense for tips. –  nyuszika7h Jul 5 '14 at 12:17

18 Answers 18

up vote 22 down vote accepted
  • The numbers 100 to 126 can be written as ?d to ?~ in 1.8.
  • On a similar note if you need a single-character string in 1.9 ?x is shorter than "x".
  • If you need to print a string without appending a newline, $><<"string" is shorter than print"string".
  • If you need to read multiple lines of input $<.map{|l|...} is shorter than while l=gets;...;end. Also you can use $<.read to read it all at once.
  • If you're supposed to read from a file, $< and gets will read from a file instead of stdin if the filename is in ARGV. So the golfiest way to reimplement cat would be: $><<$<.read.
share|improve this answer
?x yields the ascii code in general, so you can realistically get all the printables to digits in two characters. 1.9 is different, 'a'.ord yields the ascii number, but is four bytes longer than the decimal version. –  Hiato Feb 3 '11 at 8:03
You can use ?a.ord in 1.9, but that's still longer than the decimal. –  Nemo157 Feb 3 '11 at 22:59
An even golfier way to implement cat is to leave the ruby file completely empty (0 bytes) and insist that it should be run from the command line with the -p flag. –  daniero Jul 17 '13 at 20:01
or, from @daniero's own answer, puts *$< –  Not that Charles Jul 2 '14 at 19:15

Use the splat operator to get the tail and head of an array:

tail, *head = [1,2,3]
tail => 1
head => [2,3]

This also works the other way:

*head, tail = [1,2,3]
head => [1,2]
tail => 3

Use the * method with a string on arrays to join elements:

=> "1,2,3"
share|improve this answer
  • Use abort to terminate the program and print a string to STDERR - shorter than puts followed by exit
  • If you read a line with gets, you can then use ~/$/ to find its length (this doesn't count a trailing newline if it exists)
  • Use [] to check if a string contains another: 'foo'['f'] #=> 'f'
  • Use tr instead of gsub for character-wise substitutions: '01011'.tr('01','AB') #=> 'ABABB'
  • If you need to remove trailing newlines, use chop instead of chomp
share|improve this answer
+1 for abort and ~/$/ –  J-_-L Jun 26 '11 at 22:13

Use the short predefined variables wherever possible, e.g. $* instead of ARGV. There's a good list of them here, along with a lot of other useful information.

share|improve this answer

End your end.

Try to remove end from your code.

Don't use def...end to define functions. Make a lambda with the new -> operator in Ruby 1.9. (The -> operator is a "stabby lambda", or "dash rocket".) This saves 5 characters per function.

# 28 characters
def c n

# 23 characters, saves 5

Method calls are c n or c(n). Lambda calls are c[n]. Changing each c n to c[n] costs 1 character, so if you can use c n more than 5 times, then keep the method.

All methods that take do...end blocks can take {...} blocks instead. This saves 3 to 5 characters. If the precedence of {...} is too high, then use parentheses to fix it.

# 48 characters
(?a..?m).zip (1..5).cycle do|a|puts a.join','end

# WRONG: passes block to cycle, not zip
(?a..?m).zip (1..5).cycle{|a|puts a.join','}

# 45 characters, saves 3
(?a..?m).zip((1..5).cycle){|a|puts a.join','}

Replace if...else...end with the ternary operator ?:. If a branch has two or more statements, wrap them in parentheses.

# 67 characters
if a<b
puts'statement 1'
puts'statement 2'else
puts'statement 3'end

# 62 characters, saves 5
a<b ?(puts'statement 1'
puts'statement 2'):(puts'statement 3')

You probably don't have while or until loops, but if you do, then write them in modifier form.

b-=1)while a<b
share|improve this answer

Scientific notation can often be used to shave off a char or two:

share|improve this answer
Note: This will return a Float value (1000.0) instead of an Integer, which may cause inaccurate results with large numbers. –  Dogbert Feb 25 '11 at 11:02
Ah, nice 1e2 is better than 100.0 when a percentage is needed. –  Phrogz Feb 26 '11 at 6:36

If you need to find if a particular element e is inside a range r, you can use


instead of the longer:

r.cover?(e) # only works if `r.exclude_end?` is false




share|improve this answer
Isn’t r===e even shorter? –  akuhn Jun 1 '12 at 21:10
@akuhn Yes, it is. Much Shorter. Thanks for pointing that out, it helped me shorten my code by 10 chars, which is huge: codegolf.stackexchange.com/a/6125/3527 –  w0lf Jun 1 '12 at 21:20
You’re welcome. Everything that can be used in a switch statement has === implemented. –  akuhn Jun 2 '12 at 12:49

$_ is last read line.

  • print - if no argument given print content of $_
  • ~/regexp/ - short for $_=~/regexp/

In Ruby 1.8, you have four methods in Kernel that operate on $_:

  • chop
  • chomp
  • sub
  • gsub

In Ruby 1.9, these four methods exist only if your script uses -n or -p.

If you want to print some variable often then use trace_var(:var_name){|a|p a}

share|improve this answer
These are only available when you run Ruby with the -p or -n option. Reference. –  Darren Stone Dec 27 '13 at 19:12

Build arrays using a=i,*a to get them in reverse order. You don't even need to initialize a, and if you do it doesn't have to be an array.

share|improve this answer

If the first line starts with #! and contains ruby, then Ruby will take command-line switches from it.

For example, if you require two libraries, you can golf



#!ruby -rbenchmark -rprime

which saves 7 bytes.

share|improve this answer
Or you can just add -rbenchmark -rprime to the character/byte count. That's usual in choice golf. –  nyuszika7h Jul 5 '14 at 12:21

Use || instead or and && instead and.

Beside the one character from and you can save the spaces (and perhaps the bracket) around the operator.

p true and false ? 'yes' :'no'   #-> true (wrong result)
p (true and false) ? 'yes' :'no' #-> 'no'
p true&&false ? 'yes' :'no'      #-> 'no', saved 5 characters

p true or false ? 'yes' :'no'   #-> true (wrong result)
p (true or false) ? 'yes' :'no' #-> 'yes'
p true||false ? 'yes' :'no'      #-> 'yes', saved 4 characters

If you loop on an array you normally use each. But map loops also over an array and it is one character shorter.

share|improve this answer

Use Goruby instead of Ruby, which is something like an abbreviated version of Ruby. You can install it with rvm via

rvm install goruby

Goruby allows you to write most of your code as you would be writing Ruby, but has additional abbreviations built in. To find out the shortest available abbreviation for something, you can use the helper method shortest_abbreviation, for example:

shortest_abbreviation :puts
#=> "pts"

Array.new.shortest_abbreviation :map
#=> "m"

String.new.shortest_abbreviation :capitalize
#=> "cp"

Array.new.shortest_abbreviation :join
#=> "j"

Also very handy is the alias say for puts which itself can be abbreviated with s. So instead of

puts [*?a..?z].map(&:capitalize).join

you can now write

s [*?a..?z].m(&:cp).j

to print the alphabet in capitals (which is not avery good example). This blog post explains more stuff and some of the inner workings if you are interested in further reading.

PS: don't miss out on the h method ;-)

share|improve this answer

I just attempted a TDD code-golf challenge i.e. Write shortest code to make specs pass. The specs were something like

describe PigLatin do
  describe '.translate' do
    it 'translates "cat" to "atcay"' do
      expect(PigLatin.translate('cat')).to eq('atcay')
    # And similar examples for .translate

For the sake of code-golf, one need not create a module or class.

Instead of

module PigLatin def self.translate s;'some code'end;end

one can do

def(PigLatin=p).translate s;'some code'end

Saves 13 characters!

share|improve this answer
Ha, very thorough. Not only did you add the necessary behavior to PigLatin, but also to @pig_latin, $pig_latin, and 'pig'['latin']. –  histocrat Feb 27 '14 at 15:23

Kernel#p is a fun method.

Use p var instead of puts var. This works perfectly with integers and floats, but not with all types. It prints quotation marks around strings, which is probably not what you want.

Used with a single argument, p returns the argument after printing it.

Used with multiple arguments, p returns the arguments in an array.

Use p (with no arguments) instead of nil.

share|improve this answer
Unfortunately p 'some string' prints "some string" and not just some string which is often criticised by others. –  Patrick Oscity Jun 1 '13 at 21:11

You can re-write things like this:

p 1 while 1


p 1 if 1

Like this:

p 1while 1


p 1if 1

It's not a useful example, but it could be used for other things.

share|improve this answer

Don't use the true and false keywords.


  • !p for true (thanks, histocrat!)
  • !0 for false

to save some chars.

share|improve this answer
Unless you actually need true (i.e. if a truthy value is enough, like in an if condition), you don't even need !!. –  Martin Büttner Aug 6 '14 at 6:31
And similarly, p (which evaluates to nil) is a shorter falsey value. Which means the shortest way to get true is !p. –  histocrat Aug 6 '14 at 22:17
@histocrat good point! I've edited my answer. –  w0lf Aug 7 '14 at 6:26

Use string interpolation!

  1. To replace to_s. If you need parentheses around whatever you want to turn into a string, to_s is two bytes longer than string interpolation:

  2. To replace concatenation. If you concatenate something surrounded by two other strings, interpolation can save you one byte:


    Also works if the middle thing is itself concatenated, if you just move the concatenation inside the interpolation (instead of using multiple interpolations):

share|improve this answer

When working with arrays, .compact can be replaced with -[nil] to save 2 chars.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.