Confusion with wrapper methods and Proc object

Some sentences are making me confused from the link.

define_method always defines a method without the tricks, even if a
non-lambda Proc object is given. This is the only exception for which
the tricks are not preserved.

class C
define_method(:e, &proc {})
end
C.new.e(1,2) #=> ArgumentError
C.new.method(:e).to_proc.lambda? #=> true

This exception insures that methods never have tricks and makes it
easy to have wrappers to define methods that behave as usual.

The line made me confused, I put inside . Now what official doc
meant by the line ?

Dear Arup,

I’ve never digged this deeper in methods, procs and lambdas, but, I’ll
give my try on it…

p = proc { |a, b| [a, b] }

p.lambda? #=> false

So it HAVE tricks, and the parameters are “optional”

p.parameters #=> [[:opt, :a], [:opt, :b]]

l = lambda { |a, b| [a, b] }

l.lambda? #=> true

So it doesn’t have tricks, and the parameters are required

l.parameters #=> [[:req, :a], [:req, :b]]

But, if I create this lambda from a proc object, it preserves the

tricks

l = lambda(&p)

l.lambda? #=> false

l.parameters #=> [[:opt, :a], [:opt, :b]]

So, you could be fooled that a method also behave the same.

You could think that a method created from a proc would preserve the

tricks also.

But this is an exception, methods don’t have tricks, even if they

were created from a proc

So the text advises you "This is the only exception for which the

tricks are not preserved."

define_method(:m, &p)

m(1) #=> ArgumentError, so it doesn’t have tricks

method(:m).to_proc.lambda? #=> true

Your doubt: This exception insures that methods never have tricks and
makes it easy to have wrappers to define methods that behave as usual.

When defining a proc or lambda, I don’t care if it behave or not
behave as what it is (a proc can behave as a lambda and vice versa).
But, when you see a method calling like m(1,2) you can always expect
it will behave without tricks. No matter how it was created.

I hope it clarifies a little bit.

Best regards,
Abinoam Jr.

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