Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - using class instance to access same named methods from different modules

Tags:

module

ruby

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

like image 441
rahoolm Avatar asked Aug 23 '26 09:08

rahoolm


1 Answers

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 ..."
like image 172
Arup Rakshit Avatar answered Aug 25 '26 05:08

Arup Rakshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!