A
Artur Merke
Hi,
I'm just studing some metaprogramming and came across some problems.
The following code:
####################
class D
instance_eval do
define_method("i_method") do
print "\nin i_method"
end
def ii_method
print "\nin ii_method"
end
end
class_eval do
define_method("c_method") do
print "\nin c_method"
end
def cc_method
print "\nin cc_method"
end
end
end
D.new.i_method
D.ii_method
D.new.c_method
D.new.cc_method
D.i_method
##################
results in
in i_method
in ii_method
in c_method
in cc_method
metaruby2.rb:163: undefined method `i_method' for D:Class (NoMethodE
rror)
so why is
D.i_method wrong and
D.new.i_method correct?
BTW, I know the right way of solving this, but I'm somehow missing
something which would explain it to me in a consitent manner
here the solution:
class D
(class << self; self; end).instance_eval do #class_eval also does
the job
define_method( :iii_method ) do
print "\nin iii_method"
end
end
end
D.iii_method
which works fine.
Artur
I'm just studing some metaprogramming and came across some problems.
The following code:
####################
class D
instance_eval do
define_method("i_method") do
print "\nin i_method"
end
def ii_method
print "\nin ii_method"
end
end
class_eval do
define_method("c_method") do
print "\nin c_method"
end
def cc_method
print "\nin cc_method"
end
end
end
D.new.i_method
D.ii_method
D.new.c_method
D.new.cc_method
D.i_method
##################
results in
in i_method
in ii_method
in c_method
in cc_method
metaruby2.rb:163: undefined method `i_method' for D:Class (NoMethodE
rror)
so why is
D.i_method wrong and
D.new.i_method correct?
BTW, I know the right way of solving this, but I'm somehow missing
something which would explain it to me in a consitent manner
here the solution:
class D
(class << self; self; end).instance_eval do #class_eval also does
the job
define_method( :iii_method ) do
print "\nin iii_method"
end
end
end
D.iii_method
which works fine.
Artur