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.

instance_evalについて

Posted at

instance_evalの役割・特徴

  • instance_evalにブロックを渡すor文字列を引数で渡して、特異クラスを定義
  • ローカル変数は引き継ぐ
  • 文字列を渡した場合は特異クラスにネスト
class C
  CONST = "CONST in C"
end
hoge = "hoge"
CONST = "CONST in main"

c1 = C.new
c1.instance_eval(<<-EOS)
  CONST = "CONST in singleton_c1"
  p hoge
  p Module.nesting
  p CONST
EOS

c2 = C.new
c2.instance_eval do
  CONST = "CONST in singleton_c2"
  p hoge
  p Module.nesting
  p CONST
end

文字列実行結果

ネストが特異クラスになるのでCONSTは特異クラスで初めて定義される

"hoge"
[#<Class:#<C:0x000000000500fb18>>]
"CONST in singleton_c1"

ブロック実行結果

ネストが特異クラスの外になるのでCONSTは外側のものを上書きすることになる

rex.rb:17: warning: already initialized constant CONST
rex.rb:5: warning: previous definition of CONST was here
"hoge"
[]
"CONST in singleton_c2"
0
0
0

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?