Skip to content

Instantly share code, notes, and snippets.

@RedFred7
Last active October 3, 2015 19:30
Show Gist options
  • Save RedFred7/ec11c2324809dd72ace5 to your computer and use it in GitHub Desktop.
Save RedFred7/ec11c2324809dd72ace5 to your computer and use it in GitHub Desktop.
three different ways to create a list from another list
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