Question

The part I don't understand is how to make this yield so that the elements in the array have the calculation, (which is specified in the block), done to them if block_given?, prior to their being added together.

For example, the calculation could be |x| x+3 (to add 3 to each of the elements), but I want this to work for any sort of manipulation of the elements, such as |x| x**3 or |x| x*5, so that the elements inmy_ary ([1,2,3]) are changed as specified by the calculation.

So essentially I'm asking what I need to do to the part of my code that reads yield array.each{|x|} if block_given? . what I was trying to do here is say that each element in the array should have whatever is stated in the block done to the element, so that it is changed.

What I am passing to the this is something along the lines of my_ary.sum(2) {|x| x **4}.

class MyArray
  attr_reader :ary

  def init(ary)
    @ary = ary
  end

  def sum(init_val = 0)
    yield ary.each{|x|} if block_given? 
    (@ary.inject(0){|x,y|x+y}) + init_val 
  end
end
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top