class MyArray
attr_reader :ary
def initialize(ary)
@ary = ary
end
def sum n, &block
new_ary = @ary.collect &block # ary after executing block
ary_sum = new_ary.inject(0){|sum, x| sum+=x} # sum all elements of the array
return ary_sum + n
end
end
def nsum n, &block
, here &
saves the block (code between {}
or do; end
) to instance of Proc
. It's basically your block of code saved to variable.
@ary.collect &block
here, collect
want block
not proc
so &
change proc
to the block
. collect
execute block for each element, and return new array.
inject
- yields element to the block, add it to sum
, and it is returned as sum
variable. On the next iteration (next yielding to the block) sum
will be last value of previous iteration.
[1,2,3].inject(0){|s, x| s+=x}
# sum = 0; x = 1;
# sum = 1; x = 2
# sum = 3; x = 3
# sum = 6
# inject returns 6 because there is no elements in the array