Overriding constructors

Posted by demas on Stack Overflow See other posts from Stack Overflow or by demas
Published on 2010-04-03T05:55:34Z Indexed on 2010/04/03 6:03 UTC
Read the original article Hit count: 270

Filed under:

Here is sample code:

class One
  def initialize(*args)
    case args.size
    when 0
      puts "one initialize"
    when 1
      puts "one initialize #{args[0]}"
    end
  end
end

class Two
  def initialize(*args)
    if args.size == 2 then
      puts "two initialize #{args[0]} and #{args[1]}"
    else
      super(args)
    end
  end
end

one = One.new
one = One.new("thing")

two = Two.new("some", "other")
two = Two.new("some")

Now I'm launching the code and getting the error message:

[[email protected]][~/temp]% ruby test2.rb
 one initialize
 one initialize thing
 two initialize some and other
 test2.rb:17:in `initialize': wrong number of arguments(1 for 0) (ArgumentError)
   from test2.rb:17:in `initialize'
   from test2.rb:26:in `new'
   from test2.rb:26:in `<main>'

How can I call parent's constructor from class Two ?

© Stack Overflow or respective owner

Related posts about ruby