[Ruby] [Ruby] Maybe you don’t understand? [Difference between class and module]

3 minute read

Hello Ichihara.

Before

“I often use it in apps made with Rails **I want to put my own method in a separate file and use it where necessary **, but I do not know how to do it …”

There was such a thing. It seems that I know it unexpectedly, but I did not understand **class and module **, so I summarized it in the article.

calss and modules

It is like this when roughly summarized.

  Features Usage Inheritance Instance Superiority
class A collection of data and methods Load a file with require and then inherit it to use as an instance method Use multiple frameworks by using inheritance. Can do
module A collection of only methods and values Used by include and extend after reading the file with reequire Collected data and used as required parts, used as parts

class

Classes affect a wider range of objects through inheritance and instantiation.

``


class Formula
  def pythagorean_theorem(a, b)
    p "c = #{Math::sqrt(a**2+ b**2)}"
  end

  def self.quadratic_formula(a, b, c)
    x1 = (- b +Math::sqrt(b*b -4*a*c))/2 * a
    x2 = (- b -Math::sqrt(b*b -4*a*c))/2 * a
    p "x is #{x1} and #{x2}"
  end
end


``

calc/calculate.rb
First read the file using # require
require "calc/formulas"

# Inherit class and inherit methods and data
class Hoge <Formula

  attr_accessor :name

  def initialize(name, age)
    @name = name
    @age = age
  end

end

hoge = Hoge.new("hogehoge",22)
hoge.pythagorean_theorem(3, 4)

#------------------------------------------------- ----------

"c = 5.0"

In the case of a class, first the file is read using require, the class you want to use is inherited, and then instance is created.

Therefore, it is suitable for a lot of data such as MVC model and framework construction Inheriting and linking with each other, but if you want to use a little data collectively, it will be described later. It can be said that module is more suitable.

module

Modules also have the role of collecting the same values and methods as class, but instance creation and inheritance are not possible.

Therefore, modules are easier to use than classes in terms of simply collecting the information and calling it at the required location.

There are two types of calling module in class: include and extend.

include and extend

In short, include includes module as instance method and extend includes module as class method.

In the following, **mathematical formulas are summarized as a module and called as an instance method. **

``

calc/formulas.rb
module Formula

# The Pythagorean theorem
  def pythagorean_theorem(a, b)
    p "c = #{Math::sqrt(a**2+ b**2)}"
  end


  # Solution formula
  def quadratic_formula(a, b, c)
    x1 = (- b +Math::sqrt(b*b -4*a*c))/2 * a
    x2 = (- b -Math::sqrt(b*b -4*a*c))/2 * a
    p "x is #{x1} and #{x2}"
  end

end

``

calc/calculate.rb
# Read
require "calc/formulas"

class Hoge

  attr_accessor :name
  
  # Use include in class
  include Formula

  def initialize(name, age)
    @name = name
    @age = age
  end

end


hoge = Hoge.new("hogehoge",22)
hoge.pythagorean_theorem(3, 4)

#------------------------------------------------- -

"c = 5.0"

In this way, the instance generated from the Hoge class can use Pythagorean theorem pythagorean_theorem as an instance method.

Then read it in the same way with extend…

``


require "calc/formulas"

class Hoge
  attr_accessor :name

  extend Formula

  def initialize(name, age)
    @name = name
    @age = age
  end

  def hello
    p "Hello! I'm #{@name} "
    p "I'm #{@age} old"
  end

end

hoge = Hoge.new("hogehoge",22)
hoge.pythagorean_theorem(3, 4)

#------------------------------------------------- -------------------

calculate.rb:26:in `<main>': undefined method `pythagorean_theorem' for #<Hoge:0x000000000504a3a8 @name="hogehoge", @age=22> (NoMethodError)

And you can see that the created instance cannot use the methods of module.

``


Hoge.pythagorean_theorem(3, 4)

#------------------------------------------------- ---------------

"c = 5.0"

You can use it by calling it as a class method.

By the way, since the module is expanded in class, you can use instance method and class method in the class that inherits it **

The following inherited a class using include.

``



class Fuga <Hoge

end


fuga = Fuga.new("fugafuga",20)
fuga.quadratic_formula(1, 3, 2)

#------------------------------------------------- ---------------
"x is -1.0 and -2.0"

module method

If you just want to use methods directly without incorporating them into classes, you can use **module methods.

``


module Formula

  def pythagorean_theorem(a, b)
    p "c = #{Math::sqrt(a**2+ b**2)}"
  end

  def quadratic_formula(a, b, c)
    x1 = (- b +Math::sqrt(b*b -4*a*c))/2 * a
    x2 = (- b -Math::sqrt(b*b -4*a*c))/2 * a
    p "x is #{x1} and #{x2}"
  end
 
 # module_function + method name defines module method
  module_function :quadratic_formula

end

``


# Can be called in the same way as class methods
Formula.quadratic_formula(1, 8, 12)

#------------------------------------------------- -

"x is -2.0 and -6.0"

As you can see, module isn’t necessary until you create a class, but you can use it if you want to add some features**.

Summary

It is preferable to use module if you just want to collect data, and class if you want to embed data in a part of the application using inheritance.

Tags: ,

Updated: