self.module_eval?

  • Thread starter Douglas Livingstone
  • Start date
D

Douglas Livingstone

Why does this work:

class ComplexObject
attr_accessor :colour
def initialize # :yield: c
ComplexObject.module_eval "undef_method :colour="
end
end

But this doesn't?

class ComplexObject
attr_accessor :colour
def initialize # :yield: c
self.module_eval "undef_method :colour="
end
end

(btw, I know about attr_reader, I'm just looking for ways around the
"disadvantages" for "Initializing complex objects" at
http://www.rubygarden.org/ruby?RubyIdioms )

I assumed that self == ComplexObject, but obviously not... why is that?

Cheers,
Douglas
 
J

James Edward Gray II

Why does this work:

class ComplexObject
attr_accessor :colour
def initialize # :yield: c
ComplexObject.module_eval "undef_method :colour="
end
end

But this doesn't?

class ComplexObject
attr_accessor :colour
def initialize # :yield: c
self.module_eval "undef_method :colour="
end
end

(btw, I know about attr_reader, I'm just looking for ways around the
"disadvantages" for "Initializing complex objects" at
http://www.rubygarden.org/ruby?RubyIdioms )

I assumed that self == ComplexObject, but obviously not... why is that?

When initialize() gets called, "self" will be setup to point to the
current object, as is always true with Ruby instance methods. If you
want to fetch the object's class, without hardcoding it, use
"self.class..."

Hope that helps.

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top