Last active
October 3, 2015 19:30
-
-
Save RedFred7/ec11c2324809dd72ace5 to your computer and use it in GitHub Desktop.
three different ways to create a list from another list
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
require 'benchmark' | |
@arr = (1..100000).to_a | |
def rookie_way | |
new_arr = [] | |
@arr.each do |x| | |
if x % 2 == 0 | |
new_arr << x * 3 if x * 3 < 20 | |
end | |
end | |
new_arr | |
end | |
def chainsaw | |
@arr.select{|x| x % 2 == 0 }.map{|x| x * 3}.reject{|x| x > 19} | |
end | |
def in_between | |
@arr.map{|x| x * 3 if x % 2 == 0 && x * 3 < 20}.compact | |
end | |
r = 100 | |
Benchmark.bmbm do |bm| | |
bm.report(:rookie_way) { rookie_way } | |
bm.report(:chainsaw) { chainsaw } | |
bm.report(:in_between) { in_between } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment