Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Ruby Blocks Working With Blocks Implementing Block Methods

Hajun Lee
Hajun Lee
895 Points

Similar 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
Francois van der Hoven
2,026 Points

Hi 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