Forum: Ruby how do I make the block running

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Roelof Wobben (Guest)
on 2014-06-24 21:59
(Received via mailing list)

    <meta http-equiv="content-type" content="text/html;
  <body text="#000000" bgcolor="#FFFFFF">
    Hello, <br>
    Suppose I have this : <code>my_array.sum(0) {|n| n ** 2 }<br>
      I can do yield if block_given? <br>
      But thent the block is not executed. <br>
      If I have this class :<br>
      class MyArray<br>
      &nbsp; attr_reader :array<br>
      &nbsp; def initialize(array)<br>
      &nbsp;&nbsp;&nbsp; @array = array<br>
      &nbsp; end<br>
      &nbsp; def sum(initial_value = 0)<br>
      &nbsp;&nbsp;&nbsp; return yield if block_given? <br>
      &nbsp;&nbsp;&nbsp; array.inject(:+) + initial_value&nbsp;&nbsp;
      &nbsp; end<br>
      Where does the block get saved. <br>
      I can make a block with contains the block but I think there is a
      better way ?<br>
C297e10b07782381cfdc8f659aece7be?d=identicon&s=25 Joo J. (joo_j)
on 2014-06-24 22:58
Err, is that Rails?
If not I have no idea,
if so, you might get more help in the rails section...
7f7f6930bf1af19e4adc43ac3f723834?d=identicon&s=25 Abinoam J. (abinoampraxedes_m)
on 2014-06-24 23:27
(Received via mailing list)
Dear Roelof Wobben,

You can capture the given block like:

def my_method(&block)

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
Jesús Gabriel y Galán (Guest)
on 2014-06-24 23:45
(Received via mailing list)
On Tue, Jun 24, 2014 at 9:58 PM, Roelof Wobben <> wrote:
> class MyArray
> end
> Where does the block get saved.
> I can make a block with contains the block but I think there is a better way
> ?

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

def sum(initial_value = 0, &blk)


and then 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), :+)

Untested, but could give you some ideas.

Roelof Wobben (Guest)
on 2014-06-25 08:13
(Received via mailing list)
Jes??s Gabriel y Gal??n schreef op 24-6-2014 23:44:
>, :+)

Thanks all.

I can now do the Ruby Monk Primer Ascent tutorial.

This topic is locked and can not be replied to.