简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM