Forum: Ruby hand over block to a submethod

Posted by bernhard stoecker (stoecki)
on 2012-09-11 12:31
hi @ all,

lets assume I have two methods in class Func

class Func

  def self.mean(array)
    return 0 if(array.size == 0)
    if(block_given?)
      return array.map{|x| yield(x)}.sum.to_f / array.size
    end
    return array.sum.to_f / array.size
  end



  def self.variance(array)
    return 0 if array.size == 0
    avr = Func.mean(array) #HOW TO HAND OVER A BLOCK???

    if(block_given?)
      return array.map { |i| (yield(i) - avr)**2 }.sum / array.size
    end
    return array.map { |i| (i - avr)**2 }.sum / array.size

  end

end


my problem is, that i have to hand over the block given to variance to
the mean method. is this possible and if yes how?

thanks in advance

greets bernhard
Posted by "Jesús Gabriel y Galán" <jgabrielygalan@gmail.com> (Guest)
on 2012-09-11 12:52
(Received via mailing list)
On Tue, Sep 11, 2012 at 12:31 PM, bernhard stoecker
<lists@ruby-forum.com> wrote:
>     end
>       return array.map { |i| (yield(i) - avr)**2 }.sum / array.size
>
> thanks in advance
>
> greets bernhard
>
> --
> Posted via http://www.ruby-forum.com/.
>

1.9.2p290 :001 > def test
1.9.2p290 :002?>   if block_given?
1.9.2p290 :003?>     puts "I have a block"
1.9.2p290 :004?>     yield
1.9.2p290 :005?>     else
1.9.2p290 :006 >       puts "no block"
1.9.2p290 :007?>     end
1.9.2p290 :008?>   end
 => nil
1.9.2p290 :011 > def other &blk
1.9.2p290 :012?>   puts "passing block"
1.9.2p290 :013?>   test &blk
1.9.2p290 :014?>   end
 => nil
1.9.2p290 :015 > other
passing block
no block
 => nil
1.9.2p290 :018 > other {puts "I'm the block"}
passing block
I have a block
I'm the block
 => nil

Jesus.
Posted by Robert Klemme (robert_k78)
on 2012-09-11 12:53
(Received via mailing list)
On Tue, Sep 11, 2012 at 12:31 PM, bernhard stoecker
<lists@ruby-forum.com> wrote:
> my problem is, that i have to hand over the block given to variance to
> the mean method. is this possible and if yes how?

You can reference the block passed to the current method with & and
also use that notation to forward it to another method:

def m1(a,b,c,d, &bl)
  m2(x, y, z, &bl)
end

def m2
  yield 1
end

Kind regards

robert
Posted by bernhard stoecker (stoecki)
on 2012-09-11 13:53
cool! thanks to you guys
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.