Proble with closures

Please help. I have jruby script file and need to define closure
callback function that can call script member. How to do this?

latch = CountDownLatch.new(1)

def callback()
latch.countDown()
end

class Proxy
def call()
callback()
end
end

proxy = Proxy.new()

proxy.call()

when I run it as is I got an exception -> Can’t find latch.

This syntax as you wrote…

callback = ->{ latch.countDown() }

… don’t want to compile but another one compiled successful

callback = lamda { latch.countDown() }

But it does not work too and I get this error

undefined local variable or method `callback’ for #Proxy:0x13c4c09

This is more a Ruby question, but I’ll answer here.

Method definitions are not closures, as you found here. What you want
is a Ruby block:

latch = CountDownLatch.new(1)

callback = ->{ latch.countDown() }

Every call to callback.call will then call latch.countDown.

  • Charlie

On Wed, Jun 20, 2012 at 9:56 AM, Yurij P. [email protected] wrote:

But it does not work too and I get this error

undefined local variable or method `callback’ for #Proxy:0x13c4c09

That’s the same problem, just pushed to a new reference. Without
questioning why you’re wanting your methods to be closures, here’s a
version that would work:

require ‘java’
import ‘java.util.concurrent.CountDownLatch’

latch = CountDownLatch.new(1)

callback = lambda { latch.countDown }

class Proxy
def initialize(callback)
@callback = callback
end
def call()
@callback.call
end
end

proxy = Proxy.new(callback)

proxy.call()

Or if you REALLY want those methods to be closures, define them with
blocks, rather than with def.

require ‘java’
import ‘java.util.concurrent.CountDownLatch’

latch = CountDownLatch.new(1)

callback = lambda { latch.countDown }

class Proxy
end

Proxy.class_eval do
define_method :call, do
callback.call
end
end

proxy = Proxy.new()

proxy.call()

But, again, before you start doing trickery like that, consider why
you’re going down this road.

Many thanks, just 2 minutes ago I tried push callback in intialize
constructor and it works.

Where can I read more about syntax of that statements?

Proxy.class_eval do
define_method :call, do
callback.call
end
end

Hi Yurij!

http://www.google.com/search?q=ruby+1.9+new+lambda+syntax

http://pragdave.blogs.pragprog.com/pragdave/2008/05/new-lambda-synt.html

http://www.spritle.com/blogs/2011/05/16/three-new-things-in-ruby-1-9-x/

On 2012-06-20, at 17:16, Yurij P. wrote:

Many thanks, just 2 minutes ago I tried push callback in intialize
constructor and it works.

Where can I read more about syntax of that statements?

Proxy.class_eval do
define_method :call, do
callback.call
end
end


Uwe K.
http://ruboto.org/