Forum: Ruby how can I invoke the 'include' in the class instance function

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
4a691970d23098ca00ec5780774ace4b?d=identicon&s=25 Jarod Zhu (Guest)
on 2008-11-19 16:01
(Received via mailing list)
For same reason, I want to invoke the 'include' in the class instance
function.
The code like this:
******************************************************************************************
class QQ
 module QQ_Elem
   def print_elem
     puts "elem"
   end
 end

 def test
   include QQ_Elem
   print_elem
   puts "test"
 end
end

qq = QQ.new
qq.test
******************************************************************************************
But I got the error like this:
in `test': undefined method `include' for #<QQ:0x2bb5150>
(NoMethodError)

Is there anyone know the solution?
Thank you
D71ee781fc01856cc187c3ce14374c80?d=identicon&s=25 Mikael Hilund (Guest)
on 2008-11-19 16:27
(Received via mailing list)
On Nov 19, 2008, at 15:56, Jarod Zhu wrote:
> But I got the error like this:
> in `test': undefined method `include' for #<QQ:0x2bb5150>
> (NoMethodError)

Call it on the class instead, as in `self.class.include QQ_Elem`.

However, since it's only supposed to be called from within the class
itself (not an instance of the class), it's marked as private. To
circumvent this, call `self.class.send :include, QQ_Elem`.
A246f7c0ce5f2909483d358bd9e83e4e?d=identicon&s=25 Mike Gold (mikegold)
on 2008-11-19 16:40
Jarod Zhu wrote:
> For same reason, I want to invoke the 'include' in the class instance
> function.

class QQ
  module QQ_Elem
    def print_elem
      puts "elem"
    end
  end

  def test
    extend QQ_Elem   # <-----------
    print_elem
    puts "test"
  end
end

qq = QQ.new
qq.test #=> elem
        #   test
This topic is locked and can not be replied to.