Re: Generation of initialize



Trans wrote:

On Oct 31, 4:10 pm, arcadiorubiogar...@xxxxxxxxx wrote:
Hi again,

I'm trying to enhance the previous solution (shown again at the end).
I'd like to call the initialize method of the superclass from the
generated initialize. For the moment it's ok to call it without
parameters. Simply placing super inside the method definition doesn't
work. Can anyone explain me how to do it. Thanks in advance.

Why doesn't it work?

def initialize_with(*params)
define_method(:initialize) do |*args|
if args.size != params.size then
raise ArgumentError.new("wrong number of arguments"\
" (#{args.size} for #{params.size})")
end
super() if defined?(super)
params.zip(args) do |param, arg|
instance_variable_set("@#{param}", arg)
end
end
return params
end

The "()" on super clears the auto-passing of parameters.

It seems to work (if this is what you meant):

module HasInitializeWith
def initialize_with(*params)
define_method(:initialize) do |*args|
if args.size != params.size then
raise ArgumentError.new("wrong number of arguments"\
" (#{args.size} for #{params.size})")
end
super() if defined?(super)
params.zip(args) do |param, arg|
instance_variable_set("@#{param}", arg)
end
end
return params
end
end

class A
extend HasInitializeWith
self.initialize_with :foo
end

p A.new(3) # ==> #<A:0xb7c28cbc @foo=3>

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

.



Relevant Pages

  • Re: Generation of initialize
    ... I'd like to call the initialize method of the superclass from the ... Simply placing super inside the method definition doesn't ... params.zip(args) do |param, arg| ... module HasInitializeWith ...
    (comp.lang.ruby)
  • Re: Generation of initialize
    ... I'd like to call the initialize method of the superclass from the ... Simply placing super inside the method definition doesn't ... params.zip(args) do |param, arg| ... The "" on super clears the auto-passing of parameters. ...
    (comp.lang.ruby)
  • Re: Thread: super should be first line or last line?
    ... super when subclassing a thread you will get an initialization error. ... So ok we throw a super in the initialize method and that clears things ...
    (comp.lang.ruby)
  • Re: Generation of initialize
    ... I'd like to call the initialize method of the superclass from the ... params.zip(args) do |param, arg| ...
    (comp.lang.ruby)
  • Re: overriding NArray.new
    ... > normally give an NArray if it wasn't a Sound so that NArray's ... > initialize method gets called. ... I do want to call super. ...
    (comp.lang.ruby)