fc2ブログ

2023.09 «  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 - - - - » 2023.11
TOP > 定数や変数の実験・その4【インスタンス変数の実験】

 ← 定数や変数の実験・その5【クラス変数の実験】 | TOP | 定数や変数の実験・その3【ローカル変数の実験】

定数や変数の実験・その4【インスタンス変数の実験】 

2007年08月29日 ()
シリーズもので Ruby の変数や定数の実験をしています。

1.定数の実験
2.グローバル変数の実験
3.ローカル変数の実験
4.インスタンス変数
5.クラス変数の実験

今回は、4.インスタンス変数の実験の実験をしてみました。


インスタンス変数の実験1

@hensu = 'hensu_data'
@hensu = 'hensu_data_new' # もちろん値を書き換えられる

class MyClass
  @hensu = 'hensu_data_in_class'
  def method1
    p @hensu
  end
  def method2
    @hensu = 'hensu_data_in_method2'
    p @hensu
  end
end

p @hensu # -> "hensu_data_new"

my_instance = MyClass.new
my_instance.method1 # -> nil ※注:"hensu_data_in_class"とは表示されないんだ。へえー。
my_instance.method2 # -> "hensu_data_in_method2"
my_instance.method1 # -> "hensu_data_in_method2" ※注:method2 の中で @hensu に設定した値が共有される

p @hensu # -> "hensu_data_new"




インスタンス変数の実験2

class MyClass
  def method1
    p @hensu
  end
  def method2
    @hensu = 'hensu_data_in_method2'
    p @hensu
  end
end

class MyChildClass < MyClass
  def child_method1
    p @hensu
  end
  def child_method2
    @hensu = 'hensu_data_in_child_method2'
    p @hensu
  end
end

my_instance = MyClass.new
my_child_instance = MyChildClass.new

my_instance.method2 # -> "hensu_data_in_method2" ※注:親クラスの @hensu の値を書き換えてみる

my_child_instance.child_method1 # -> nil ※注:親クラスの @hensu の値が書き換えられても子クラスの @hensu には影響ない
my_child_instance.method2 # -> "hensu_data_in_method2" ※注:子クラスの @hensu として値が設定された
my_child_instance.child_method1 # -> "hensu_data_in_method2" ※注:子クラスの @hensu の値が共有される

my_child_instance.child_method2 # -> "hensu_data_in_child_method2" ※注:子クラスの @hensu の値を書き換えてみる
my_instance.method1 # -> "hensu_data_in_method2" ※注:子クラスの @hensu の値が書き換えられても親クラスの @hensu には影響ない




Ruby の変数や定数の命名規則は、こちらからどうぞ。

【広告】

[2007.08.29(Wed) 00:29] Rubyの文法Trackback(0) | Comments(0)
↑TOPへ

 ← 定数や変数の実験・その5【クラス変数の実験】 | TOP | 定数や変数の実験・その3【ローカル変数の実験】

COMMENT

COMMENT POST















管理者にだけ表示

 ← 定数や変数の実験・その5【クラス変数の実験】 | TOP | 定数や変数の実験・その3【ローカル変数の実験】