Forum: Ruby how do I make the block running

39d8572ef267bc6771f1ef52527a9784?d=identicon&s=25 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>
2b2cb3c6e72a6dd85581489990272f56?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...
09a32175057418748822c587ac08c429?d=identicon&s=25 Abinoam Jr. (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
E088bb5c80fd3c4fd02c2020cdacbaf0?d=identicon&s=25 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.

39d8572ef267bc6771f1ef52527a9784?d=identicon&s=25 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.

Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.