0
\$\begingroup\$

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?

\$\endgroup\$
3
  • 5
    \$\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\$ Commented 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\$ Commented Dec 17, 2020 at 2:25
  • \$\begingroup\$ @AlterLagos : I was not aware, that sum can take a block. May I suggest that you post this as answer? \$\endgroup\$ Commented Aug 26, 2024 at 12:48

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.