Reputation: 773
I have 2 Modules M1 and M2 each containing same method name as met1
I have a class MyClass which includes these modules. I create an instance test of MyClass, now I want to call met1 from each module. Is it possible to do so?
here is the code:
module M1
def met1
p "from M1 met1.."
end
end
module M2
def met1
p "from M2 met1 ..."
end
end
class MyClass
include M1, M2
def met2
p "met2 from my class"
end
end
test = MyClass.new
test.met1 # From module 1
test.met2 # from my class
test.met1 # from module 2 (how to ?)
Please let me know how to do this.
My output is
"from M1 met1.."
"met2 from my class"
"from M1 met1.."
This might be a very simple query but please answer. Thanks
Upvotes: 3
Views: 547
Reputation: 118271
now I want to call met1 from each module. Is it possible to do so?
Yes,possible. Use Module#instance_method
to create first UnboundMethod
. Then do call UnboundMethod#bind
to bind test
object. Now you have Method
object with you. So call now Method#call
to get your expected output.
module M1
def met1
p "from M1 met1.."
end
end
module M2
def met1
p "from M2 met1 ..."
end
end
class MyClass
include M1, M2
def met2
p "met2 from my class"
end
end
test = MyClass.new
test.class.included_modules.each do |m|
m.instance_method(:met1).bind(test).call unless m == Kernel
end
# >> "from M1 met1.."
# >> "from M2 met1 ..."
Upvotes: 4