Tips for golfing in Ruby

  • 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.

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

head, *tail = [1,2,3]
head => 1
tail => [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 an array to join elements:

[1,2,3]*?,
=> "1,2,3"

  • 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