Is there a way to use "def self.new" to do the job of "def initialize"?

Hi.
In Ruby, if I want to make an instance of a class C, the syntax is

c = C.new

But to define how that instance is initialized I need to make a method
called “initialize”, not “new”. Like so:

class C
attr_reader :a
def initialize
@a = "a"
end
end

I was curious, is there a way to do the initialization in a method "C.new"
without defining an “initialize” method?
Something like this:

class C
attr_reader :a
def C.new
# initialization
# return new instance of C
end
end

Why? Mostly curiousity. Ever since I’ve noticed the assymmetry between the
initialization syntax (c=C.new) and the initialization definition (def
initialize rather than def C.new) I’ve wondered if it would be possible to
use a more symmetrical method.

I realize that this is completely unneccessary and that people are happy
with the mechanisms that are in place, it’s just that, for me, this a bit of
an itch to scratch.

Thank you for your time and attention,
Sean

Sean Ross wrote:

class C
attr_reader :a
def C.new
# initialization
# return new instance of C
end
end

Well, keep in mind that in C.new, @a is not accessible. Thus, unless
‘a’ is a writable attribute, the C.new method cannot directly write to
it (thus the existence of the initialize method, to do instance-specific
initialization).

However, with eval magic, you can do it:

def C.new( a )
obj = allocate
obj.instance_eval { @a = a }
obj
end

It just feels kind of klunky to me (and an invasion of C’s privacy) to
use instance_eval like that…

  • Jamis
···


Jamis Buck
jgb3@email.byu.edu

ruby -h | ruby -e ‘a=;readlines.join.scan(/-(.)[e|Kk(\S*)|le.l(…)e|#!(\S*)/) {|r| a << r.compact.first };puts “\n>#{a.join(%q/ /)}<\n\n”’

“Jamis Buck” jgb3@email.byu.edu wrote in message
news:3FE9DDF4.5070009@email.byu.edu…

However, with eval magic, you can do it:

def C.new( a )
obj = allocate
obj.instance_eval { @a = a }
obj
end

It just feels kind of klunky to me (and an invasion of C’s privacy) to
use instance_eval like that…

Hi.

Thank you. I agree it does feel “klunky”. But it can be done. Very cool.
I won’t use it, I just wanted to know whether it could be done.

Thanks for satisfying my curiousity,
Sean

Thank you. I agree it does feel “klunky”. But it can be done. Very cool.
I won’t use it, I just wanted to know whether it could be done.

It has its uses. Look in the net/http code and you’ll find some clever
coding.

Ari