Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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 do not you register as a user and use Qiita more conveniently?
  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
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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