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
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.