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

···

--
Posted via http://www.ruby-forum.com/.

Chinna Karuppan wrote:

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

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

···

--
Posted via http://www.ruby-forum.com/\.

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 11:00:28 -0500, Chinna Karuppan wrote:

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

--
Ken (Chanoch) Bloom. PhD candidate. Linguistic Cognition Laboratory.
Department of Computer Science. Illinois Institute of Technology.
http://www.iit.edu/~kbloom1/

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

···

2008/3/19, Chinna Karuppan <chinnakaruppan@gmail.com>:

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

--
Posted via http://www.ruby-forum.com/\.

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

--Ken

···

On Wed, 19 Mar 2008 12:23:58 -0500, Mateusz Tybura 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

--
Ken (Chanoch) Bloom. PhD candidate. Linguistic Cognition Laboratory.
Department of Computer Science. Illinois Institute of Technology.
http://www.iit.edu/~kbloom1/