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