Re: Generation of initialize
- From: Joel VanderWerf <vjoel@xxxxxxxxxxxxxxxxx>
- Date: Thu, 1 Nov 2007 05:53:20 +0900
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
.
- References:
- Re: Generation of initialize
- From: arcadiorubiogarcia
- Re: Generation of initialize
- From: Trans
- Re: Generation of initialize
- Prev by Date: Re: JRuby perf questions answered
- Next by Date: Re: JRuby perf questions answered
- Previous by thread: Re: Generation of initialize
- Next by thread: why, or when to, use a class method?
- Index(es):
Relevant Pages
|