Last active
August 29, 2015 13:56
-
-
Save havenwood/9181208 to your computer and use it in GitHub Desktop.
Enumerable#peek_at an index.
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
module Enumerable | |
def peek_at index | |
value, _ = each_with_index.select { |_, i| index == i }.first | |
value | |
end | |
end |
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
['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"] |
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
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