LoginSignup
34
33

More than 5 years have passed since last update.

動的なメソッドの呼び出し

Posted at

呼び出すメソッドが動的に変わる場合のメソッドの呼び出し方法のメモ。

制御構造で分ける場合

call_method_case.rb
def get_id
  return 256
end

def get_name
  return 'エナジー炭酸 がぶ飲み POWER SQUASH' # いまハマってる
end

# nameが欲しい
data_type = :name

# caseで処理を分ける
case data_type
when :id then p get_id
when :name then p get_name

メタプログラミングの場合

call_method_meta.rb
def get_id
  return 64
end

def get_name
  return 'A&W ROOT BEER' # ホントはこっちのほうが好き
end

# nameが欲しい
data_type = 'name'
#sendでメソッドを呼び出す
p send("get_#{data_type}")
34
33
3

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
34
33