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 trial

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