Created
November 27, 2012 10:36
-
-
Save jmeirow/4153547 to your computer and use it in GitHub Desktop.
Alternate Version of #to_range
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 | |
| 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.