Skip to content

Instantly share code, notes, and snippets.

@apeiros
Created February 10, 2012 19:03
Show Gist options
  • Save apeiros/1791790 to your computer and use it in GitHub Desktop.
Save apeiros/1791790 to your computer and use it in GitHub Desktop.
Enumerable#last, halfway scalable
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