Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes the 'planets align' condition of select.last vs reverse.detect #122

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions code/enumerable/select-last-vs-reverse-detect.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,30 @@
ARRAY = [*1..100]

def fast
# "It just happens to line up" case
ARRAY.reverse.detect { |x| (x % 10).zero? }

# "Middle of the road" case
# ARRAY.reverse.detect { |x| ((x % 10) == 60) }

# "Worst Case" scenario
# ARRAY.reverse.detect { |x| x == 1 }
end

def slow
# "It just happens to line up" case
ARRAY.select { |x| (x % 10).zero? }.last

# "Middle of the road" case
# ARRAY.select { |x| ((x % 10) == 60) }.last

# "Worst Case" scenario
# ARRAY.select { |x| x == 1 }.last
end

Benchmark.ips do |x|
x.report('Enumerable#reverse.detect') { fast }
x.report('Enumerable#select.last') { slow }
x.compare!
end