From: Stefano Crocco Date: 2013-02-18T03:23:28+09:00 Subject: Re: What is Ruby's default constructor? On Monday 18 February 2013 Love U Ruby wrote > Hi, > > I wrote the below class : > >> class Adder > > ?> def initialize(my_num) > > >> @my_num = my_num > >> > >> end > > ?> end > => nil > > >> ob = Adder.new > > ArgumentError: wrong number of arguments (0 for 1) > from (irb):3:in `initialize' > from (irb):8:in `new' > from (irb):8 > from /usr/bin/irb:12:in `
' > > #~~~> Here it is not allowing the creation of object.Even does not > allowing automatic call to its default constructor which it does when a > class has been defined without "initialize" method. > > >> ob = Adder.new(10) > > => # > > #~~~> here it is OK. and it should be. > > #~~> then in the below class how object is created, what constructor it > has called? > > >> class A > >> p "hi" > >> end > > "hi" > => "hi" > > >> ob = A.new > > => # > > > -- > Posted via http://www.ruby-forum.com/. What you call ruby's default constructor is, in fact, Object#initialize, which takes no argument and does nothing. When you define an #initialize method in your class, that method will be called from the class .new method and all the arguments passed to .new will in turn be passed to #initialize. Since you defined Adder#initialize to take one argument, you have to pass Adder.new one argument (or give a default value to the argument of Adder#initialize). As for calling the default constructor when Adder.new is given no arguments, this is something which never happens in ruby. If you override a method in a derived class (#initialize is not special in any way), the overriding method is the one which will always be called, even if the arguments are wrong. I hope this helps Stefano