Let's say I have this array.
items = [
{
amount: 100,
add: true
},
{
amount: 50,
add: false
},
{
amount: 100,
add: true
}
]
What I want to do is add the amount if add is true and subtract it if add is false.
This code uses an extra total variable.
total = 0
items.each do |item|
if item[:add]
total += item[:amount]
else
total -= item[:amount]
end
end
A one-liner code.
items.sum { |item| item[:add] ? item[:amount] : -item[:amount] }
I wonder if there is a better implementation for this problem. Is the one-liner readable enough?
items.sum { |add:, amount:| add ? amount : -amount }\$\endgroup\$sumcan take a block. May I suggest that you post this as answer? \$\endgroup\$