Based on the following example should I conclude whether I use
instance_eval or class_eval, define_method always creates an instance
method.
class Music
end
Music.instance_eval do
define_method :jazz do
puts ‘i am jazz’
end
end
Music.class_eval do
define_method :rock do
puts ‘i am rock’
end
end
Music.jazz rescue puts ‘Music.jazz failed’
Music.rock rescue puts ‘Music.rock failed’
Music.new.jazz rescue puts ‘Music.new.jazz failed’
Music.new.rock rescue puts ‘Music.new.rock failed’
output is:
Music.jazz failed
Music.rock failed
i am jazz
i am rock
From: Raj S. [mailto:[email protected]]
Based on the following example should I conclude whether I use
instance_eval or class_eval, define_method always creates an instance
method…
Hi Raj,
you may need to access Music’s meta/eigenclass in order to define a
singleton for it.
eg, in ruby 1.8.6 latest stable
irb(main):044:0> def add_class_method(c, m, &b)
irb(main):045:1> eigenclass = class << c; self; end
irb(main):046:1> eigenclass.class_eval {
irb(main):047:2* define_method(m, &b)
irb(main):048:2> }
irb(main):049:1> end
=> nil
irb(main):050:0>
irb(main):051:0* add_class_method(Music, :rock2) do
irb(main):052:1* puts ‘i am a rock, too :)’
irb(main):053:1> end
=> #Proc:0x028c6c00@:51(irb)
irb(main):054:0> Music.rock2
i am a rock, too
=> nil
irb(main):056:0> [RUBY_VERSION,RUBY_PATCHLEVEL,RUBY_RELEASE_DATE,
RUBY_PLATFORM
]
=> [“1.8.6”, 286, “2008-08-08”, “i386-mswin32”]
in 1.9, it is much simpler
irb(main):002:0> class Music
irb(main):003:1> end
=> nil
irb(main):004:0> Music.define_singleton_method(:rock) do
irb(main):005:1* puts “i am a classy rock”
irb(main):006:1> end
=> #<Proc:0xe033dc@(irb):5 (lambda)>
irb(main):007:0> Music.rock
i am a classy rock
=> nil
irb(main):008:0> RUBY_VERSION
=> “1.9.0”
kind regards -botp