ruby - Dose self.class.class_eval equal to instance_eval? -
i want find out difference between instance_eval , class_eval,so did work。after searching internet, figure out something, there comes other question can't understand!when i'm doing this:
class findme def method_missing method, *args, &block method = method.to_s self.class.class_eval <<-eof, __file__, __line__ def #{method} puts "i'm instance method! i'm #{method}" end eof send method, *args end def self.method_missing method, *args, &block method = method.to_s instance_eval <<-here, __file__, __line__ def #{method} puts "i'm class method! i'm #{method}" end here send method, *args end end findme.new.hello findme.hello
i
i'm instance method! i'm hello i'm class method! i'm hello
when change code :
class findme def method_missing method, *args, &block method = method.to_s self.class.class_eval <<-eof, __file__, __line__ def #{method} puts "i'm instance method! i'm #{method}" end eof send method, *args end def self.method_missing method, *args, &block method = method.to_s self.class.class_eval <<-here, __file__, __line__ def #{method} puts "i'm class method! i'm #{method}" end here send method, *args end end findme.new.hello findme.hello
i same output, can 1 tell what's going on?
by class_eval
modify class, instance_eval
current instance only. look:
▶ class ▷ def ceval ▷ self.class.class_eval "def on_class ; puts 'on class' ; end" ▷ end ▷ def ieval ▷ self.instance_eval "def on_instance ; puts 'on instance' ; end" ▷ end ▷ end ▶ a1 = a.new #⇒ #<a:0xcf6a87c> ▶ a1.ceval #⇒ :on_class ▶ a1.ieval #⇒ :on_instance ▶ a1.on_class #⇒ on class ▶ a1.on_instance #⇒ on instance ▶ a2 = a.new #⇒ #<a:0xd0e9f7c> ▶ a2.on_class #⇒ on class !!! defined on newly created instance of ▶ a2.on_instance #⇒ nomethoderror: undefined method `on_instance' #<a:0xd0e9f7c>
the latter fails because declare on_instance
method on instance a1
, , a2
knows nothing it.
Comments
Post a Comment