3

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

1 Answer 1

4

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 ..."
Sign up to request clarification or add additional context in comments.

3 Comments

+1. Is it just me, or is SO somewhat dead these days?
By the way, could you please explain me what does m == Kernel exactly means?
@rahoolm Object is a default superclass of MyClass. Object includes Kernel. So Kernel is included in MyClass too. But meth is not defined in that Kernel module.Thus to avoid Kernel, I used that if condition. Just do test.class.included_modules,you will get to see that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.