Let's say I have this array.

items = [
{
amount: 100,
},
{
amount: 50,
},
{
amount: 100,
}
]


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|
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?

• The one-line solution looks readable enough to me. A shorter version could be using keyword arguments: items.sum { |add:, amount:| add ? amount : -amount } Dec 16, 2020 at 23:18
• @AlterLagos I have been doing that with JavaScript. I don't know you can do that in Ruby. I can use that knowledge more in the future. Thanks. Dec 17, 2020 at 2:25