Created
October 26, 2012 08:36
-
-
Save paulspringett/3957649 to your computer and use it in GitHub Desktop.
Focus on elements in an Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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