Skip to content

Instantly share code, notes, and snippets.

@jmeirow
Created November 27, 2012 10:36
Show Gist options
  • Select an option

  • Save jmeirow/4153547 to your computer and use it in GitHub Desktop.

Select an option

Save jmeirow/4153547 to your computer and use it in GitHub Desktop.
Alternate Version of #to_range
class Array
def to_range
self.sort!
highs = self.select { |x| !self.include?(x+1) }
lows = self.select { |x| !self.include?(x-1) }
lows.zip(highs).map { |a,b| a..b }
end
end
@darrencauthon
Copy link

We can't do that, as it has an after-effect in that the original array is altered. So if I do this:

array = [3, 2, 1]
array.to_range
array # will equal [1, 2, 3]

If we were going to alter the original and follow standard Ruby conventions, we'd have to put an exclamation point at the end of the method name to signify that it alters the original.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment