instance_eval with method proc

P

Paul Carey

Hi

I'm trying to invoke a method defined in one class with self set to an
instance of a different class. I didn't have much success (as shown
below). Is there another way to achieve this?

Many thanks

Paul

----

class Foo
def foo
print
end

def print
puts "foo"
end

def test bar
foo_proc = Proc.new { print }

# Prints bar
bar.instance_eval(&foo_proc)

# 1.8.6 Fails with "wrong number of arguments (1 for 0) (ArgumentError)"
# 1.9.1 Prints foo
bar.instance_eval(&method:)foo))
end
end

class Bar
def print
puts "bar"
end
end

Foo.new.test Bar.new
 
B

Brian Candler

Paul said:
I'm trying to invoke a method defined in one class with self set to an
instance of a different class.

If the method is in a common superclass, then you can make an
UnboundMethod and bind it to the new object. e.g.

But otherwise I don't think you can detach arbitrary methods from one
class and apply them to an object of an unrelated class. You'd probably
be best putting the relevant method(s) in a mixin, and then sharing that
between the classes, or adding those methods to the singleton class of
the individual object you're interested in.
baz!
=> nil
 
B

Brian Candler

Brian said:
If the method is in a common superclass, then you can make an
UnboundMethod and bind it to the new object. e.g.

... and of course, object b usually has the 'foo' method already
inherited from the parent, in which case b.send:)foo) is sufficient.

But if 'foo' has been overridden, it can still be useful to bind this
way.
foo from child
=> nilfoo from parent
=> nil
 
P

Paul Carey

I'm trying to invoke a method defined in one class with self set to an
You'd probably be best ... or adding those methods to the singleton
class of the individual object you're interested in.

Thanks Brian, I went with adding the methods to the singleton class.
Paul
 

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
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top