Created
April 16, 2013 16:59
-
-
Save antifuchs/5397589 to your computer and use it in GitHub Desktop.
Array#sorted? method for discovering whether an array is sorted in any order. Optionally takes a block and yields to it each element to discover the sort value for that element.
This file contains 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 sorted?(&block) | |
case length | |
when 0, 1 then true | |
else | |
init_signum = nil | |
if block | |
init_signum = block.call(self[0]) <=> (prev = block.call(self[1])) | |
else | |
init_signum = self[0] <=> (prev = self[1]) | |
end | |
for i in 2...self.length | |
elt = self[i] | |
elt = block.call(elt) if block | |
if (prev <=> elt) != init_signum | |
return false | |
end | |
prev = elt | |
end | |
return true | |
end | |
end | |
def sortage(&block) | |
if block | |
values = self.map(&block) | |
else | |
values = self.dup | |
end | |
prev = values.shift | |
values.map {|elt| res = prev <=> elt; prev = elt ; res} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I guess the
#sortage
method should go on some other module and not clutter up Array's public methods.