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]
    total -= item[:amount]

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?

  • 4
    \$\begingroup\$ The one-line solution looks readable enough to me. A shorter version could be using keyword arguments: items.sum { |add:, amount:| add ? amount : -amount } \$\endgroup\$ Dec 16, 2020 at 23:18
  • \$\begingroup\$ @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. \$\endgroup\$
    – dcangulo
    Dec 17, 2020 at 2:25


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.