Skip to content

Instantly share code, notes, and snippets.

@pacso
Created January 21, 2016 08:20
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 pacso/f7e997593bd15bd121d1 to your computer and use it in GitHub Desktop.
Save pacso/f7e997593bd15bd121d1 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
def products
[
{"dt" => "2016-01-01",
"quantity" => 122,
"amount" => 123000
},
{"dt" => "2016-01-02",
"quantity" => 97,
"amount" => 97800
},
{"dt" => "2016-01-03",
"quantity" => 142,
"amount" => 163000
}
]
end
def array_each
rowqty = 0
rowamount = 0
products.each do |row|
rowqty += row['quantity']
rowamount += row['amount']
row['total_quantity'] = rowqty
row['total_amount'] = rowamount
end
end
def array_inject
products.inject([0, 0]) do |data, product|
data[0] += product['quantity']
data[1] += product['amount']
product['total_quantity'] = data[0]
product['total_amount'] = data[1]
data
end
end
Benchmark.ips do |x|
x.report('Using Array#each') do
array_each
end
x.report('Using Array#inject') do
array_inject
end
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment