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 thanprint"string"
. - If you need to read multiple lines of input
$<.map{|l|...}
is shorter thanwhile l=gets;...;end
. Also you can use$<.read
to read it all at once. - If you're supposed to read from a file,
$<
andgets
will read from a file instead of stdin if the filename is inARGV
. So the golfiest way to reimplementcat
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 thanputs
followed byexit
- 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 ofgsub
for character-wise substitutions:'01011'.tr('01','AB') #=> 'ABABB'
- If you need to remove trailing newlines, use
chop
instead ofchomp