5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby の #class_eval と #module_eval の違い

Posted at

ブログ記事からの転載です

Ruby の #class_eval はクラスオブジェクト専用、#module_eval はモジュールオブジェクト専用のメソッドだと思っていたのですが、実は名前が違うだけで同等のメソッドだったみたい。

検証コード

class C
end

C.class_eval {
	def homu
	end
}

# クラスオブジェクトに対しても #module_eval が使える
C.module_eval {
	def mami
	end
}

p C.instance_methods false
# => [:homu, :mami]


module M
end

# モジュールオブジェクトに対しても #class_eval が使える
M.class_eval {
	def homu
	end
}

M.module_eval {
	def mami
	end
}

p M.instance_methods false
# => [:homu, :mami]

結論

#class_eval#module_eval の違いは名前だけなのでケースによってよしなに使い分けましょう。

参照

5
0
0

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
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?