Les Bases Du Golfing En Ruby

Want to start golfing?

Let’s start with a « classic » solution that we could write to solve a CodinGame problem.

# 367 chars
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.

persons = gets.to_i
heights = []
ages = []
persons.times do
    age, height = gets.split(" ").collect {|x| x.to_i }
    heights << height
    ages << age
end

# Write an action using puts
# To debug: STDERR.puts "Debug messages..."

puts ages.max, heights.min
  • Remove comments
    # 180 chars
    persons = gets.to_i
    heights = []
    ages = []
    persons.times do
      age, height = gets.split(" ").collect {|x| x.to_i }
      heights << height
      ages << age
    end
    puts ages.max, heights.min
    
  • Trim spaces
    # 155 chars
    persons=gets.to_i
    heights=[]
    ages=[]
    persons.times do
    age,height=gets.split(" ").collect{|x|x.to_i}
    heights<<height
    ages<<age
    end
    puts ages.max,heights.min
    
  • Use only 1 Char variables names
    # 102 chars
    p=gets.to_i
    h=[]
    a=[]
    p.times do
    x,y=gets.split(" ").collect{|x|x.to_i}
    h<<y
    a<<x
    end
    puts a.max,h.min
    
  • No need to give parameters by default to the methods (split here)
    # 97 chars
    p=gets.to_i
    h=[]
    a=[]
    p.times do
    x,y=gets.split.collect{|x|x.to_i}
    h<<y
    a<<x
    end
    puts a.max,h.min
    
  • When multiple aliases exist for the same function, use the shorter (map vs collect vs each)
    # 93 chars
    p=gets.to_i
    h=[]
    a=[]
    p.times do
    x,y=gets.split.map{|x|x.to_i}
    h<<y
    a<<x
    end
    puts a.max,h.min
    
  • Use _1 as block’s parameters (_1 stores the block’s first parameter, _2 stores the second one if using .each_with_index for example, etc)
    # 91 chars
    p=gets.to_i
    h=[]
    a=[]
    p.times do
    x,y=gets.split.map{_1.to_i}
    h<<y
    a<<x
    end
    puts a.max,h.min
    
  • Replace simple blocks with the function’s symbol to apply
    # 90 chars
    p=gets.to_i
    h=[]
    a=[]
    p.times do
    x,y=gets.split.map(&:to_i)
    h<<y
    a<<x
    end
    puts a.max,h.min
    
  • Replace the do ... end with brackets
    # 86 chars
    p=gets.to_i
    h=[]
    a=[]
    p.times{
    x,y=gets.split.map(&:to_i)
    h<<y
    a<<x
    }
    puts a.max,h.min
    
  • Avoid useless line breaks
    # 84 chars
    p=gets.to_i
    h=[]
    a=[]
    p.times{x,y=gets.split.map(&:to_i)
    h<<y
    a<<x}
    puts a.max,h.min
    
  • Remove parenthesis at the end of chained functions (on the map here)
    # 83 chars
    p=gets.to_i
    h=[]
    a=[]
    p.times{x,y=gets.split.map &:to_i
    h<<y
    a<<x}
    puts a.max,h.min
    
  • Do not assign variables that we’ll use only once
    # 79 chars
    h=[]
    a=[]
    gets.to_i.times{x,y=gets.split.map &:to_i
    h<<y
    a<<x}
    puts a.max,h.min