Code Golfing Tips

Navigation

Recent site activity

Ruby

Reading from standard in

  • Kernel#gets normally retrieves one line at a time. To get the entire contents of STDIN, pass it nil.

    gets p

    Example
    usage: reverse entire inputSolution

    You can also use the STDIN IO variable $<, but this is one byte longer (or equal, if using gets(p)), so often not worthwhile. It evaluates to true when tested as a boolean, which may be useful.

    $<.read

    Example usage:
    reverse entire inputSolution

  • String#split splits on whitespace by default. But pass it an empty RegExp, and it splits the string into individual characters.

    while gets.split //

    Often, using Kernel#getc is superior to the above. However, the characters are returned as numbers (0..255) rather than strings.

    while getc

Writing to standard out

  • For printing numbers with a newline, you can use use Kernel#p.

    p 24

  • For printing anything else without a newline, you can usually use the STDOUT variable $>. Note that all the other printing methods return nil... this method returns an IO object, which evaluates to true in boolean tests.

    $><<24

Looping
  • As nice as Enumerable#each is for readability, it is actually rather bloated for total character count. Try using Enumerable#map or inline while instead.

    gets.split(//).map{|i|...}
    (...)while gets   # The parenthesis are unnecessary if there is only one statement in the while.
Other Ruby tricks
  • Kernel#p does nothing and returns nil. That makes it a short way to get nil or false.

    gets p

  • Numbers from 100 to 255 can be specified using ?d syntax, which returns the byte value of the following character. You might need a hex editor to insert high-byte characters.

    100==?d