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

Refinementでクラスメソッドを再定義する

方法1

singleton_classを使う

class MyClass
  def self.my_method
    'MyClass.my_method'
  end
end

module MyModule
  refine MyClass.singleton_class do
    def my_method
      'Myclass.my_method in MyModule'
    end
  end
end

using MyModule

puts MyClass.my_method # Myclass.my_method in MyModule

方法2

selfを使わずクラスメソッドを定義

class MyClass
  def self.my_method
    'MyClass.my_method'
  end
end

module MyModule
  refine MyClass do
    def MyClass.my_method
      'Myclass.my_method in MyModule'
    end
  end
end

using MyModule

puts MyClass.my_method # Myclass.my_method in MyModule

もしくは

class MyClass
  def self.my_method
    'MyClass.my_method'
  end
end

module MyModule
  refine MyClass do
    class << MyClass
      def my_method
        'Myclass.my_method in MyModule'
      end
    end
  end
end

using MyModule

puts MyClass.my_method # Myclass.my_method in MyModule

selfの場合

うまく呼び出すことができない

class MyClass
  def self.my_method
    'MyClass.my_method'
  end
end

module MyModule
  refine MyClass do
    def self.my_method
      'Myclass.my_method in MyModule'
    end
  end
end

using MyModule

puts MyClass.my_method # 'MyClass.my_method'
tamugramer
元事務屋のアラサープログラマー
yowayowa-engineer
弱々エンジニア会とは駆け出しエンジニアやベテランエンジニアまで、弱々から強々まで幅広く集まるコミュニティのエンジニア集団です!!メンバー募集してますので気になる方は、URLよりSlackに参加ください!条件等は特にありません!
https://join.slack.com/t/yowayowa-engineer/shared_invite/zt-c227e3jr-uQ~0NOZU4xaiZjNLe_E8hg
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
Comments
No 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
ユーザーは見つかりませんでした