class::new :: --> NUBY

C

Chinna Karuppan

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 class `KK'

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
 
M

Mark Bush

Chinna said:
class KK
alias oldnew new
NameError: undefined method `new' for class `KK'

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 :eek:ldnew, :new
def new
yield if block_given?
oldnew
end
end

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

Ken Bloom

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 class `KK'

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?
 
M

Mateusz Tybura

[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
 
K

Ken Bloom

[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
 

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

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top