Tools for clean code
In teams, a linter keeps the style uniform: RuboCop is the big configurable one with hundreds of rules, Standard the zero-discussion variant (“one config for everyone”). More important than any single rule: the team stops arguing about commas. Add YARD for doc comments and – if you like – type signatures with RBS or Sorbet.
$ gem install standard
$ standardrb # checks the style
$ standardrb --fix # repairs a lot by itself
# And for breakpoint debugging right in your code:
require "debug"
binding.break # or binding.irb - opens a console RIGHT HEREBut debugging works everywhere – including here. The universal tool is p: it prints its argument and returns it, so you can sneak it into the middle of any chain:
values = [3, 1, 4, 1, 5, 9]
values.select { |x| p(x).odd? }.sumWhy p and not puts? Because puts doesn't show everything: nil and an empty string turn into empty lines, and an array falls apart into single lines. p shows the honest representation, the one from inspect:
values = ["bacon", nil, "", 42]
puts values
p valuesSo when a value looks strangely empty, ask p rather than puts. Related helpers: pp wraps nested data nicely, and caller shows who called the current method.
round_to should round minutes to the nearest grid (round_to(38, 15) → 45), but it always truncates. Find the bug (try p!) and repair the method.# This method should round to the NEAREST grid -
# but it returns round_to(38, 15) => 30 instead of 45. Why?
def round_to(minutes, grid)
(minutes / grid) * grid
end
round_to(38, 15)