Send() with a block?

Thanks for all the responses. This may be true:


The actual method “send” can take a block, and it passes it to the
method being invoked. If it didn’t, it would be impossible to pass a
block to a method when invoking it using send.

…but why should a beginner have to figure that out? You shouldn’t
have to be a meta-programming guru to figure out the docs. Wouldn’t it
be better if beginners posted: “I really think the docs are great.”
rather than “beginner: the docs are confusing !#[email protected]#$; expert-response:
they are clear if you are smart.”

Does the following code prove that “impossibile” statement wrong??

def my_meth(my_proc, *args)
yield
other_meth(*args, &my_proc)
end

def other_meth(*args)
yield
end

my_proc = Proc.new {puts ‘goodbye’}

my_meth(my_proc, 1, 2, 3) do
puts ‘hello’
end

–output:–
hello
goodbye

my_method() takes a block, and my_method() does not pass the block on;
it yields to the block. Yet my_method still passes a block to
other_method().

Now, why doesn’t this work:

def my_meth(*args)
yield
p args
end

my_proc = Proc.new {puts ‘hello’}
my_meth(1, 2, 3, &my_proc ) #=>‘hello’ [1, 2, 3]

obj = Object.new
m = obj.method(my_meth)
m.call([10, 20, 30], &my_proc) #No block given(LocalJumpError) at yield
line

On Mar 14, 2011, at 6:24 PM, 7stud – wrote:

obj = Object.new
m = obj.method(my_meth)
m.call([10, 20, 30], &my_proc) #LocalJumpError at yield line

Your comment about LocalJumpError should be one line above and it
occurs because you are calling my_meth without a block and are
attempting to yield to the non-existent block. You don’t want
to invoke my_meth there, you want to name it:

m = obj.method(‘my_meth’)

I think you are adding a confusing difference when you try to invoke
my_method on the last line by packaging up three arguments in an array.
If you want to follow the pattern you used when you called my_meth
directly you should be doing:

m.call(10, 20, 30, &my_proc)

Gary W.

Gary W. wrote in post #987429:

On Mar 14, 2011, at 6:24 PM, 7stud – wrote:

obj = Object.new
m = obj.method(my_meth)
m.call([10, 20, 30], &my_proc) #LocalJumpError at yield line

Your comment about LocalJumpError should be one line above and it
occurs because you are calling my_meth without a block and are
attempting to yield to the non-existent block. You don’t want
to invoke my_meth there, you want to name it:

m = obj.method(‘my_meth’)

Ah, a typo. Thanks.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs