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

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

@shimatomo

おもしろメタプログラミング/3章

3章 火曜日

目次

  • 3.1 重複問題
  • 3.2 動的メソッド
    • 3.2.1 動的に呼び出す => ハンズオン 動的メソッド呼び出し
    • 3.2.2 pry
    • 3.2.3 動的に定義する => ハンズオン 動的メソッド定義
  • 3.3 method_missing => ハンズオン method_missing
  • 3.4 クイズ:バグ退治
  • 3.5 ブランクスレート
  • 3.6 まとめ

ハンズオン 動的メソッド呼び出し

class SomeClass
  def kamezaki
    p 'my name is kamezaki'
  end

  def sasaki
    p 'my name is sasaki'
  end

  def shimada
    p 'my name is shimada'
  end

  def naaya
    p 'my name is naaya'
  end
end

some_obj.kamezaki
some_obj.sasaki
some_obj.shimada
some_obj.naaya

1, これを動的呼び出しを使って簡潔に

ハンズオン 動的メソッド定義

1, 上を動的定義を使って簡潔に

ハンズオン method_missing

1, 上をmethod_missingを使って簡潔に

todo

  • クイズ self
  • ハンズオン private

答え

動的メソッド呼び出し

class SomeClass
  def kamezaki
    p 'my name is kamezaki'
  end

  def sasaki
    p 'my name is sasaki'
  end

  def shimada
    p 'my name is shimada'
  end

  def naaya
    p 'my name is naaya'
  end
end

obj = SomeClass.new
['kamezaki', 'sasaki', :shimada, :naaya].each do |name|
  obj.send("#{name}")
end

動的メソッド定義

class SomeClass
  def initialize(name)
    define_method name do
      p "my name is #{name}"
    end
  end
end

NAMES = ['kamezaki', 'sasaki', :shimada, :naaya]

NAMES.each do |name|
  SomeClass.new(name).send("#{name}")
end

method_missing

NAMES = [:kamezaki, :sasaki, :shimada, :naaya]

class SomeClass
  def method_missing(method_name, *args)
    return unless NAMES.include?(method_name)
    p "my name is #{method_name}"
  end
end

obj = SomeClass.new

NAMES.each do |name|
  obj.send("#{name}")
end
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
1
Help us understand the problem. What are the problem?