Shortest code (Ruby)
Tips
Read inputs
a,b,c=gets.split.map(&:to_i)
STDIN.read.split("\n") #read until EOF rather than iterate
# this may be equivalent
$<.read.split("\n")
$<.read.split.drop(1) #eg: to eliminate size given
$<.to_a
$<.each{|e|p e}
# read full input
gets('')
p $_
p `dd` # read from dd
see also
String
Split string but keep multiple whitespace
msg = "Tiam his message"
msg.chomp.split.to_s # => ["Tiam", "his", "message"]
msg.chomp.split(/\s/).to_s # => ["Tiam", "his", "", "message"]
Remove multiple spaces and new lines inside of String
s = "Hello, my\n name is Michael."
s.split.join(' ') #=> "Hello, my name is Michael."
Iterate on String
"input".bytes { |c| puts c }
"input".each_char { |c| puts c }
"input".chars.map { |c| puts c } # => "input".split('').map
# not short but usefull
str.each_char.with_index { |c,i| puts c,i }
All prefix of a string
acc = ''
str.chars.map {|c| acc += c }
Formatting using String.format / sprintf
puts "%0.1f %s" % [a,b]
Hex/Binary conversion
puts "%x" % 10 # a
puts "%X" % 10 # A
puts "%#x" % 10 # 0ba , probleme 0 => gives 0 and not 0x0
"0x0a".hex # => 10
String Litteral
?[ # => "["
Character values to Strings && SO
116.chr # => "t"
[116].pack('U*') # => "t"
"t".ord # => 116
"t".unpack('U*') # => [106]
"string".bytes # => "string".chars.map(&:ord)
string to number
"1234".to_i.to_s(2)
"%b" % "1234"
Hash
h={}
h[1]^=1 #=> nil^1 -> true
h[1]^=1 #=> true^1 -> false
Array / Ruby-doc
Array from range
*(1..10) # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[*1..3, *?a..?c] # => [1, 2, 3, "a", "b", "c"]
Filter nil
[1, nil, 3, nil, nil].compact => [1, 3]
Reverse Sort
a = ["test", "test2", "s"]
a.sort_by!{|str| str.length}.reverse!
a.sort_by! { |s| -s.length } # shorter
On Looping
Apply method on each element
array.map!(&:to_i)
inject operation
array.reduce(:+) # or inject (alias)
sum
[1, 2, 3, 4].sum
repeating text
"0" * 99
Word count with Enumerable.tally
["a", "b", "c", "b"].tally #=> {"a"=>1, "b"=>2, "c"=>1}
p vs puts
call lambda
fact = -> (x){ x < 2 ? 1 : x*fact.(x-1)}
p fact.call(5)
p fact.(5)
p fact[5]
see also
- eonu/ruby-golf
- Tips for golfing in Ruby
- Code Golf tips of ruby
- ruby-codegolf
- Ruby - code-golf/code-golf GitHub Wiki - char packer trick - But doesn’t work with Codingame which count bytes
- Compression in Golf: Part I - pack(u) trick
- zip - compression
Example
Written on May 29, 2019, Last update on August 9, 2023
ruby
codegolf
codingame
string
array