withとかでこんな感じで書けた
with foo .foo_method end
これをinstance_evalを使ってRubyでやってみようヘ(^o^)ノ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo | |
def bar | |
:bar | |
end | |
def baz | |
:baz | |
end | |
end | |
barbaz = :barbaz | |
foo = Foo.new | |
foo.instance_eval do | |
p bar # => :bar | |
p baz # => :baz | |
p barbaz # => :barbaz | |
end |
こんな感じでfooを省略できる
foo.bar foo.baz
インスタンス変数とかを条件に
メソッドコールしたりできるから便利
さらに17行目みたいに、
スコープを越えてローカル変数にアクセスできるのも便利
( ̄(エ) ̄)彡☆
0 件のコメント:
コメントを投稿