0

Let's say we have a line of code that sums up all of the billable_weeks total hours, it would look something like this:

billable_weeks.map(&:total_hours).sum

What role does the & play in the above code? Couldn't we just write it as billable_weeks.map(:total_hours).sum?

Please help clear this up for me!

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
user3399101
  • 1,477
  • 3
  • 14
  • 29
  • 1
    Did you search on Stackoverflow.com ? – Arup Rakshit May 25 '14 at 15:26
  • 1
    I used to search [this way](http://stackoverflow.com/search?q=%5Bruby%5D+%22%26%3A%22) ... – Arup Rakshit May 25 '14 at 15:27
  • Check out this question: http://stackoverflow.com/q/1217088/1407656 – toniedzwiedz May 25 '14 at 15:27
  • 2
    Note: You could just do `billable_weeks.sum(:total_hours)`. This would do the SUM operation in the database, actually, since `billable_weeks` is an Active Relation object still. If it's an array then do `billable_weeks.sum(&:total_hours)` and it'll still sum like you're asking with less processing time required (doesn't have to map to a new array first). – pdobb May 25 '14 at 15:31
  • Actually, `billable_weeks.map(&:total_hours)` is shorthand form of `billable_weeks.collect { |week| week.total_hours }`. – Ashish Bista May 25 '14 at 15:49

0 Answers0