Hacker News new | ask | show | jobs
by smitherfield 2709 days ago
Yeah, a little OCD but I couldn't stand the first example (and some of the others). Here's a more reasonable implementation that doesn't special case (or more precisely wraps the special-casing in a standard library method):

  class Array
    def neighbor_sums
      map.with_index do |_, i|
        fetch(i - 1 & 0xFF_FF_FF_FF, 0) + fetch(i + 1, 0)
      end
    end
  end

  [1, 1, 1, 1].neighbor_sums # [1, 2, 2, 1]