1

I've got a method that caclulates an amount of roylaties owed to an author.

It works like this:

calculate_royalty(object_id)

Right now, I'm using it in a view and looping through each individual author's products and spitting out a number. Like this:

<%= @author.products.each do |product| %>
  <%= @author.calculate_royalty(product.id) %>
<% end %>

Right now, that gives me a single number. What I've been trying to do is load all of those numbers into an array in my model so I can total them. I trid this:

def total_author_royalties
   products do |p|
    calculate_royalty(p.id)
   end
end

But the array just returns as a hash of the product objects for that author. I figured once I have the values in the array, I can use Array.inject to add them all up.

1 Answer 1

2

Well, if calculate_royalty just returns a number, then in your loop you are not assigning it to anything, it just returns and disappears. Try pushing each royalty into an array and summing them at the end like so:

def total_author_royalties
   royalties = []
   products.each do |p|
     royalties << calculate_royalty(p.id)
   end
   royalties.sum
end

or a more concise version:

def total_author_royalties
  products.map{|p| calculate_royalty(p.id)}.sum
end
Sign up to request clarification or add additional context in comments.

2 Comments

That worked very well. Why was map the appropriate choice in this situation as opposed to .inject?
I think it's just a preference of mine, personally. Mentally I feel it makes more sense to collect the ids in an array and sum them (even if it's two distinct operations) than to write an inject method that keeps adding numbers to a growing sum. I feel like the code I propose is easier to read, but understand it's a preference. I think either answer is appropriate in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.