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

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

メソッドの中からクラス名とメソッド名を取得する

More than 3 years have passed since last update.

rubyのメソッド中において クラス名メソッド名 を取得する方法。

class Sample

  # @return [String]
  def self.class_name
    self.name   
  end

  # @return [Symbol]  
  def self.class_method_name
    __method__
  end

  # @return [String]
  def class_name
    self.class.name
  end

  # @return [Symbol]  
  def instance_method_name
    __method__
  end

end
> Sample.class_name
"Sample"

> Sample.class_method_name
:class_method_name

> sample = Sample.new
> sample.class_name
"Sample"

> sample.instance_method_name
:instance_method_name

Deprecateなメソッドが呼ばれた時など、ログを出力することに使うと良い感じ。

#{self.class.name}\##{__method__}"
ytkt
RailsやAWS Lambdaなどを使ってAPIやWebフロントエンドを書いていたり、Product Managementやったり。趣味ではホームオートメーションに力を入れたかったり。
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