Skip to content

Add Array#to_ranges #265

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions lib/core/facets/array/to_ranges.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Array

# Convert an array of values (which must respond to #succ) to an
# array of ranges.
#
# [3,4,5,1,6,9,8].to_ranges => [1..1,3..6,8..9]
#
# CREDIT: Adapted and debugged by Ryan Duryea
# from https://dzone.com/articles/convert-ruby-array-ranges

def to_ranges
array = self.compact.uniq.sort
ranges = []
if !array.empty?
# Initialize the left and right endpoints of the range
left, right = array.first, nil
array.each do |obj|
# If the right endpoint is set and obj is not equal to right's successor
# then we need to create a range.
if right && obj != right.succ
ranges << Range.new(left,right)
left = obj
end
right = obj
end
ranges << Range.new(left,right)
end
ranges
end
end
13 changes: 13 additions & 0 deletions test/core/array/test_to_ranges.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
covers 'facets/array/to_ranges'

test_case Array do

method :to_ranges do

test do
[3,4,5,1,6,9,8].to_ranges.assert == [1..1,3..6,8..9]
end

end
end