Created
February 10, 2012 19:03
-
-
Save apeiros/1791790 to your computer and use it in GitHub Desktop.
Enumerable#last, halfway scalable
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
module Enumerable | |
unless method_defined?(:last) then | |
def last(n=nil) | |
reverse_each_method = method(:reverse_each) | |
has_reverse_each = reverse_each_method && reverse_each_method.owner != Enumerable # native reverse_each needed | |
if n then | |
return_value = [] | |
if has_reverse_each then | |
reverse_each { |val| | |
return_value.unshift(val) | |
return return_value if return_value.size == n | |
} | |
else | |
each { |val| | |
return_value.push(val) | |
return_value.shift if return_value.size > n | |
} | |
end | |
else | |
if has_reverse_each then | |
reverse_each { |value| return value } | |
else | |
return_value = nil | |
each { |value| return_value = value } | |
end | |
end | |
return_value | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment