0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python to RubyAdvent Calendar 2021

Day 1

Ruby の module のインスタンス...

Last updated at Posted at 2021-12-13

はじめに

移植やってます
Python to Ruby Advent Calendar 2021

インスタンス変数

module A
  Al = 0
  @Ai = 0
  @@Aa = 0
end

class B
  include A

  Bl = 0
  @Bi = 0
  @@Bc = 0
end
p ['instance_variables: ', A.instance_variables, B.instance_variables]
p ['class_variables: ', A.class_variables, B.class_variables]

# ["instance_variables: ", [:@Ai], [:@Bi]]
# ["class_variables: ", [:@@Aa], [:@@Bc, :@@Aa]]

モジュールはインスタンス化できないけど、インスタンス変数はあるってことですね。
モジュールのクラス変数が、上記class Bにも表れているのが不思議。

[追記]
コメント欄に、ありがたい情報があります。
@scivola さん、ありがとうございます。

module A
  @Ai = 0
  @@Ac = 0

  def seti(value)
    @Ai = value
  end

  def setc(value)
    @@Ac = value
  end

  def geti
    @Ai
  end

  def getc
    @@Ac
  end
end

class B
  include A

  def seti(value)
    super
  end

  def setc(value)
    super
  end

  def geti
    super
  end

  def getc
    super
  end
end

class C
  include A

  def seti(value)
    super
  end

  def setc(value)
    super
  end

  def geti
    super
  end

  def getc
    super
  end
end


b = B.new
c = C.new
b.seti(2)
b.setc(5)
p [b.geti, b.getc, c.geti, c.getc]

# [2, 5, nil, 5]

module class B/C のインスタンス変数ですので別になっています。

メモ

  • Ruby の module を学習した
  • 道のりは遠そう
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?