Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHajun Lee
895 PointsSimilar problem
Hi - below is somewhat of a similar problem obtained from RubyMonk. The problem asks us to write a sum method that takes a block parameter (as shown on 'defsum'.) Can you please describe what "(:+)" does and what the method, generally, is interpreting?
Thank you so much
class MyArray attr_reader :array
def initialize(array) @array = array end
def sum(initial_value = 0) return array.inject(:+) + initial_value unless block_given? sum = initial_value array.each {|n| sum = sum + yield(n) } sum end end
1 Answer
Francois van der Hoven
2,026 PointsHi Hajun,
The method inject(:+)
is one of Ruby's smart array methods that applies the +
operator to all the elements of an array.
See e.g.
> arr = [2,3,4,5]
> arr.inject(:+)
=> 14
> arr.inject(:*)
=> 120