Skip to content

Instantly share code, notes, and snippets.

@antifuchs
Created April 16, 2013 16:59
Show Gist options
  • Save antifuchs/5397589 to your computer and use it in GitHub Desktop.
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.
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
@antifuchs
Copy link
Author

I guess the #sortage method should go on some other module and not clutter up Array's public methods.

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