0
module A
end 

class Klass
  include A
end

How does this include influence Klass? Does it simply put Klass into module A or do something more?

SwiftMango
  • 15,092
  • 13
  • 71
  • 136
OneZero
  • 11,556
  • 15
  • 55
  • 92

3 Answers3

1

The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins). For example, if your class defines the method "each", you can include the mixin module Enumerable and it can act as a collection. This can be confusing as the include verb is used very differently in other languages.

from here: What is the difference between include and require in Ruby?

also take a look at this page: http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html it has a verbose explanation about how include works.

Community
  • 1
  • 1
valentinas
  • 4,277
  • 1
  • 20
  • 27
1

Short Answer: If you have some methods inside your module and you use include in a class, those methods can be used in the class.

Module A
  def shout
    puts "HEY THERE!!!!"
  end
end 

class Klass
  include A
end 

# Create instance of Klass
instance = Klass.new

# Produces "HEY THERE!!!!"    
instance.shout
thank_you
  • 11,001
  • 19
  • 101
  • 185
1

include is one of the ways to include methods of a Module in another Module or Class.

Please read my article on how that affects method calls in Ruby/

Marc-André Lafortune
  • 78,216
  • 16
  • 166
  • 166
  • That link seems to be broken @Marc-AndréLafortune is the article available at an alternate location? – Max Oct 20 '15 at 11:01
  • Argh. Got a transfer that to my blog then. You can use this one: https://web.archive.org/web/20141112151444/http://tech.pro/tutorial/1149/understanding-method-lookup-in-ruby-20 – Marc-André Lafortune Oct 20 '15 at 15:16