How do I make the block running

Hello,

Suppose I have this : `my_array.sum(0) {|n| n ** 2 }

  I can do yield if block_given?

  But thent the block is not executed.

  If I have this class :

  class MyArray

    attr_reader :array

    def initialize(array)

      @array = array

    end

    def sum(initial_value = 0)

      return yield if block_given?

      array.inject(:+) + initial_value  

    end

  end

  Where does the block get saved.

  I can make a block with contains the block but I think there is a

better way ?

  Roelof

`

Dear Roelof Wobben,

You can capture the given block like:

def my_method(&block)
  block.call
end

Does this help you?

I found your text a little confusing.
Could you try to rephrase it in a more clearer way so we could try to
help you better?

Abinoam Jr.
PS: "ruby block" on google points to
http://www.reactive.io/tips/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/

···

On Tue, Jun 24, 2014 at 4:58 PM, Roelof Wobben <r.wobben@home.nl> wrote:

Hello,

Suppose I have this : my_array.sum(0) {|n| n ** 2 }

I can do yield if block_given?

But thent the block is not executed.

If I have this class :

class MyArray
  attr_reader :array

  def initialize(array)
    @array = array
  end

  def sum(initial_value = 0)
    return yield if block_given?
    array.inject(:+) + initial_value
  end
end

Where does the block get saved.
I can make a block with contains the block but I think there is a better way
?

Roelof

I think you don't want to yield. You can capture the block like this:

def sum(initial_value = 0, &blk)

end

and then blk.call to execute the block, or use &blk to pass it to
another method. If I understood correctly, you want to map all
elements of the array to the result of passing each of them to the
block, then sum the result. If so, try something like this:

def sum(initial_value=0, &blk)
  array.map(&blk).inject(initial_value, :+)
end

Untested, but could give you some ideas.

Jesus.

···

On Tue, Jun 24, 2014 at 9:58 PM, Roelof Wobben <r.wobben@home.nl> wrote:

Hello,

Suppose I have this : my_array.sum(0) {|n| n ** 2 }

I can do yield if block_given?

But thent the block is not executed.

If I have this class :

class MyArray
  attr_reader :array

  def initialize(array)
    @array = array
  end

  def sum(initial_value = 0)
    return yield if block_given?
    array.inject(:+) + initial_value
  end
end

Where does the block get saved.
I can make a block with contains the block but I think there is a better way
?

Jesús Gabriel y Galán schreef op 24-6-2014 23:44:

array.map(&blk).inject(initial_value, :+)

Thanks all.

I can now do the Ruby Monk Primer Ascent tutorial.

Roelof