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.
Jarod Z. (Guest)
on 2008-11-19 17: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
Mikael Hilund (Guest)
on 2008-11-19 17:27
(Received via mailing list)
On Nov 19, 2008, at 15:56, Jarod Z. 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`.
Mike G. (Guest)
on 2008-11-19 17:40
Jarod Z. 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.