reuse passed proc later?

D

David Gurba

Hello Everyone,

I'm new to Ruby and some of its features...

I want to do the following (with as little modfication as necessary):

call a passed block to a function at some later time... Eg.

class A

def foo(&block)
@func = block
end
end

a = A.new
num = a.func.call { print "12" }

...but func is an unknown method, and attr_accessor :func doesn't help either....

any nice solution?

David G.
 
D

David A. Black

Hello Everyone,

I'm new to Ruby and some of its features...

I want to do the following (with as little modfication as necessary):

call a passed block to a function at some later time... Eg.

class A

def foo(&block)
@func = block
end
end

a = A.new
num = a.func.call { print "12" }

...but func is an unknown method, and attr_accessor :func doesn't help either....

any nice solution?

In your example you never call foo, so @func never gets assigned to.
Is this something like what you want to do?

class A

def func(&block)
@func ||= block
end
end

a = A.new
a.func { 12 }

num = a.func.call
puts num # 12


David
 
R

Robert Klemme

David Gurba said:
Hello Everyone,

I'm new to Ruby and some of its features...

I want to do the following (with as little modfication as necessary):

call a passed block to a function at some later time... Eg.

class A

def foo(&block)
@func = block
end
end

a = A.new
num = a.func.call { print "12" }

..but func is an unknown method, and attr_accessor :func doesn't help
either....

As David said, you don't invoke foo so you don't assign to @func. You got
the order a bit wrong since you provide the block too late, i.e. when you
want to call it. The smallest change to your example might be this

class A
def foo(&block)
@func = block
end
end

a = A.new
num = a.foo { print "12" }.call


But you probably wanted

class A
attr_reader :func
def foo(&b) @func = b end
end

a = A.new
a.foo { puts "blah!" }
a.func.call

Kind regards

robet
 
S

Shashank Date

Hi,

David said:
I want to do the following (with as little modfication as necessary):

call a passed block to a function at some later time... Eg.

class A

def foo(&block)
@func = block
end
end

a = A.new
num = a.func.call { print "12" }

..but func is an unknown method, and attr_accessor :func doesn't help either....

any nice solution?

Did you mean to do this:

class A

attr_accessor :func

def foo(&block)
@func = block
end

end

a = A.new
a.foo { print "12" }
a.func.call

__END__

HTH,
-- shanko
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,160
Messages
2,570,889
Members
47,422
Latest member
LatashiaZc

Latest Threads

Top