Skip to content

Instantly share code, notes, and snippets.

@paulspringett
Created October 26, 2012 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulspringett/3957649 to your computer and use it in GitHub Desktop.
Save paulspringett/3957649 to your computer and use it in GitHub Desktop.
Focus on elements in an Array
class Array
# Public: slice Array while focusing on the given item in the array
# and padding around it
#
# item - element in the Array to focus on
# padding - Integer of the number of elements to pad by (default: 2)
#
# Examples:
# items = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t"]
#
# items.focus("g", 3)
# => ["d", "e", "f", "g", "h", "i", "j"]
#
# items.focus("b")
# => ["a", "b", "c", "d", "e"]
#
# Returns a new sliced, focused, padded Array
def focus(item, padding = 2)
length = (padding * 2) + 1
# index of item to focus on
index = self.rindex(item)
raise ArgumentError, "item must be an element in the Array" if index.nil?
# find start point of slice, but limit to starting
# at 0 or higher
start = (index - padding)
start = (start < 0) ? 0 : start
self.slice(start, length)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment