Ruby, its about the concise code

Today I reviewed a co-workers code. And in a couple of minutes we rewrote it to be as concise - yet still expressive - as it could be. This is one of the things I love about ruby.

The original code was something along the lines of

<code class="ruby">def get_new
    all = get_all
    remove_old(all)
end

def remove_old items
   new_ones = []
   items.each do |item|
       new_ones << item if item.is_new
   end
   new_ones
end
</code>

The first rewrite was to change the remove_old method to be more ruby like.

<code class="ruby">def remove_old items
    items.select do |item|
        item.is_new
    end
end
</code>

But we quickly realized that this could be even more conscise

<code class="ruby">def remove_old items
    items.select(&:is_new)
end
</code>

However wrapping a one-liner in another method seemed stupid, so instead we inlined in the calling method

<code class="ruby">def get_new
    get_all.select(&:is_new)
end
</code>

Simple, clean… Concise.