LoginSignup
2
0

More than 5 years have passed since last update.

メタプログラミングruby 6章まとめ

Posted at

bindingオブジェクト

bindingはスコープをオブジェクトにまとめたもの。bindingを使って、ローカルスコープを所得すれば、そのスコープを持ち回すことができる。

sample.rb
class MyClass
  def my_method
    @x = 1
    binding
  end
end 

b = MyClass.new.my_method
eval "@x" b # => 1

フックメソッド

reactでイベントを継承して、クラスを定義したりするように、rubyでも、クラスが継承されたときや、moduleがミックスインされたときに、コードを実行することができる。

sample.rb
class String
  def self.inherited(subclass)
    puts "#{self}#{subclass}に継承された。"
  end
end

class MyString < String; end
=> "StringはMyStringに継承された。"

inheritedの他にもincludedやprepended,extendedなどがある。

2
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
2
0