Class::new :: --> NUBY

Hi,
I was trying to redefine new in my class…like this…

class KK
alias oldnew new
def new
yield if block_given?
oldnew
end
end
NameError: undefined method new' for classKK’

why is saying no ‘new’ method…I don’t understand.
because I can say KK.new after I define the class which means the method
is there in the class hierarchy and I should be able to override its
implementation…

THnks
Chinna

Chinna K. wrote:

class KK
alias oldnew new

NameError: undefined method new' for classKK’

You are trying to alias the instance method #new which doesn’t exist.
#new is a class method so you need to alias it in the metaclass.
Something like:

class KK
end

class << KK
alias_method :oldnew, :new
def new
yield if block_given?
oldnew
end
end

(You need the class to exist first before you access the metaclass.)

On Wed, 19 Mar 2008 11:00:28 -0500, Chinna K. wrote:

end
NameError: undefined method new' for classKK’

why is saying no ‘new’ method…I don’t understand. because I can say
KK.new after I define the class which means the method is there in the
class hierarchy and I should be able to override its implementation…

THnks
Chinna

I think you want to define the constructor for class KK as:

class KK
def initialize
yield if block_given
super
end
end

Does this do what you’re trying to accomplish?

On Wed, 19 Mar 2008 12:23:58 -0500, Mateusz T. wrote:

[Note: parts of this message were removed to make it a legal post.]

Try this code:
class KK
def new
yield if block_given?
super
end
end

This won’t work, because it operates on an instance method named new.

–Ken

Try this code:
class KK
def new
yield if block_given?
super
end
end

2008/3/19, Chinna K. [email protected]:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs