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

Hello Ichihara.

Before

"I often use it in apps made with Rails ** I want to put my own methods in a separate file and use them where necessary **, but I don't know how to do it ..."

There was such a thing. I didn't understand ** class and module **, which seemed to be surprisingly known, so I summarized them in an article.

class and module

Roughly summarized, it looks like this.

Feature how to use Inheritance instance Superiority
class A collection of data and methods Read the file with require, then inherit and use it as an instance method Since multiple classes are grouped together using inheritance, it can be used like a framework.
module A collection of only methods and values Read the file with reequire and then include,Used in extend Collect data and use it where necessary, use it as a part

class

class affects a wider range of objects through inheritance and instantiation.

python


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 classes 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 read the file using ** require **, let the class you want to use ** inherit **, and then ** create an instance **.

Therefore, it is suitable for ** inheriting a lot of data such as building MVC models and frameworks and linking each other **, but if you want to use it when you want to use data collectively, it will be described later. It can be said that ** module ** is more suitable.

module

Modules also have the role of grouping the same values and methods as class, but ** cannot create and inherit instances **.

Therefore, modules are easier to use than classes in terms of simply collecting information and calling it where it is needed.

There are two types ** to call module in class, ** include and extend **.

include and extend

In a nutshell, include embeds module as ** instance method **, and extend embeds module as ** class method **.

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

calc/formulas.rb


module Formula

 #Three square 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, which is the Pythagorean theorem, as a ** instance method **.

Then, when I read it in the same way with extend ...

python


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 generated instance cannot use the method of module.

python


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 the class, you can use the instance method and class method in the class that inherits it **, respectively.

The following inherited the class using include.

python



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 want to use only ** methods directly without incorporating them into the class, you can use ** module method **.

python


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 +Define module method by method name
  module_function :quadratic_formula

end

python


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

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

"x is -2.0 and -6.0"

As you can see, module is not necessary until ** class is created, but it can be used if you want to add a little function **.

Summary

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

Recommended Posts

[Ruby] Maybe you don't really understand? [Difference between class and module]
Easy to understand the difference between Ruby instance method and class method.
Difference between class and instance
Difference between instance method and class method
Difference between interface and abstract class
[Ruby] Difference between is_a? And instance_of?
Understand the difference between each_with_index and each.with_index
Difference between instance variable and class variable
Note: Difference between Ruby "p" and "puts"
Difference between Ruby instance variable and local variable
Difference between "|| =" and "instance_variable_defined?" In Ruby memoization
[Ruby] Difference between print, puts and p
I don't really understand the difference between swift Error and NSError, so I tried to summarize it myself.
[Java] Understand the difference between List and Set
[iOS] Understand the difference between frame and bounds
Understand the difference between abstract classes and interfaces!
[Ruby] Difference between puts and return, output and return value
Ruby: Differences between class methods and instance methods, class variables and instance variables
[Ruby] Difference between methods with and without self in the class. About class methods and instance methods.
[Ruby] I thought about the difference between each_with_index and each.with_index
What is the difference between a class and a struct? ?? ??
[Ruby] Difference between receiver and object. Differences between Ruby objects and JS objects
About the difference between classes and instances in Ruby
Difference between Spring AOP and library proxy target class
Difference between vh and%
Difference between i ++ and ++ i
[Java beginner] Difference between length and length () ~ I don't know ~
About the difference between "(double quotation)" and "single quotation" in Ruby
[Ruby] About the difference between 2 dots and 3 dots of range object.
The difference between programming with Ruby classes and programming without it
Is short-circuit evaluation really fast? Difference between && and & in Java
Difference between product and variant
Difference between redirect_to and render
[Java] Difference between == and equals
Rails: Difference between resources and resources
Difference between puts and print
Difference between redirect_to and render
Difference between CUI and GUI
Difference between variables and instance variables
Difference between mockito-core and mockito-all
Difference between bundle and bundle install
Relationship between package and class
Difference between ArrayList and LinkedList
Difference between render and redirect_to
Difference between List and ArrayList
[Ruby] Difference between match / scan
Difference between .bashrc and .bash_profile
Difference between StringBuilder and StringBuffer
Difference between render and redirect_to
Difference between render and redirect_to
I don't understand Ruby 3 Ractor
[Ruby] Relationship between parent class and child class. The relationship between a class and an instance.
[Ruby] Difference between symbol variables and character string variables. About the difference between [: a] and ['a'].
Difference between render method and redirect_to
Difference between == operator and equals method
[Java] Difference between Hashmap and HashTable
[Terminal] Difference between irb and pry
Difference between == operator and eqals method
Rough difference between RSpec and minitest
[Rails] Difference between find and find_by
[JAVA] Difference between abstract and interface