Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@tamugramer

instance_evalについて

More than 1 year has passed since last update.

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
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
tamugramer
元事務屋のアラサープログラマー
yowayowa-engineer
弱々エンジニア会とは駆け出しエンジニアやベテランエンジニアまで、弱々から強々まで幅広く集まるコミュニティのエンジニア集団です!!メンバー募集してますので気になる方は、URLよりSlackに参加ください!条件等は特にありません!

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?