Write simple code
Write simple code, don’t be smart ass.
For example, we need a method that will count unique values in the array. It could be implemented in one line:
def count_uniq_values_in(arr)
arr.each_with_object(Hash.new(0)) { |item, counter| counter[item] += 1 }.keys.size
end
But you have to remember what Enumerator#each_with_object
does, what arguments go to the block and their order (it differs from reduce
!), what it returns. The code is witty but more difficult to comprehend.
It becomes even worse when your teammates have diverse background, and not everyone joined the team with huge Ruby experience under the belt.
Usually we read code more often then write it, so it should be optimized for digesting. Let’s make it better.
def count_uniq_values_in(arr)
counter = Hash.new(0)
arr.each do |item|
counter[item] += 1
end
counter.keys.size
end
It occupies 5 lines instead of 1, but now the code separated into 3 distinct parts:
- preparing data structures and variables,
- doing action,
- returning value.
The exotic each_with_object
method yields to simple each
iterator everyone got used to.
The block itself is pretty short, and could be written in one line, but I’d prefer to keep the shape that makes it look like a loop. It hints that the method could be a little bit more complex than O(1)
.