Skip to content

Instantly share code, notes, and snippets.

@DimaSamodurov
Last active December 11, 2015 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DimaSamodurov/4588754 to your computer and use it in GitHub Desktop.
Save DimaSamodurov/4588754 to your computer and use it in GitHub Desktop.
Ruby class_eval vs instance_eval
# Two great articles allow to understand Ruby better
# http://yugui.jp/articles/846
# http://yehudakatz.com/2009/11/15/metaprogramming-in-ruby-its-all-about-the-self/
class A; end
A.instance_eval { define_method(:hoge) { "hoge" } }
A.class_eval { define_method(:fuga) { "fuga" } }
A.instance_eval { def piyo ; "piyo"; end }
A.class_eval { def foo ; "foo"; end }
p A.new.hoge #=> "hoge"
p A.new.fuga #=> "fuga"
p A.piyo #=> "piyo"
p A.new.foo #=> "foo"
# Here 'define_method' can leverage closures and wider scope,
# where 'def' can serve the opposite goal and provide better isolation.
class X ; end
X.singleton_class.instance_eval do
def y
:y
end
define_method :w do
:w
end
define_singleton_method :z do
:z
end
end
X.singleton_class.y
X.w
X.singleton_class.z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment