Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/9181208 to your computer and use it in GitHub Desktop.
Save havenwood/9181208 to your computer and use it in GitHub Desktop.
Enumerable#peek_at an index.
module Enumerable
def peek_at index
value, _ = each_with_index.select { |_, i| index == i }.first
value
end
end
['a', 'b', 'c'].peek_at 2
#=> "c"
'a'.upto('c').peek_at 2
#=> "c"
('a'..'c').peek_at 2
#=> "c"
Struct.new(:a, :b, :c).new('a', 'b', 'c').peek_at 2
#=> "c"
{a: 'a', b: 'b', c: 'c'}.peek_at 2
#=> [:c, "c"]
require 'era'
time(100_000) { ['a', 'b', 'c'].peek_at 2 }
# Elapsed time: 189.518 ms
#=> "c"
time(100_000) { ['a', 'b', 'c'][2] }
# Elapsed time: 36.828 ms
#=> "c"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment