Home > Software engineering >  Ruby oneliner for defining, iterating over array, adding and returning value?
Ruby oneliner for defining, iterating over array, adding and returning value?

Time:11-03

I have this piece of code:

def total_balance
  total = 0
  users.each { |user| total  = user.balance }
  total
end

and i wonder if there is a shorter version/one liner for this?

it basically iterates over users and adds their balance together.

ty!

CodePudding user response:

def total_balance
  users.sum { |user| user.balance }
  # or users.sum(&:balance)
  # or users.map(&:balance).sum
  # or users.reduce(0) { |total, user| total  = user.balance }
  # or users.inject(0) { |total, user| total  = user.balance }
end

With the inject or reduce, I always get the accumulator and the object mixed up in the pipe variables. But that's easy to fix with debugging :D

  •  Tags:  
  • ruby
  • Related