ArgumentError: wrong number of arguments in Ruby -


trying solve problem,

  class person       def initialize(name)         @name=name       end        def greet(other_name)        puts "hi #{other_name}, name #{name}"       end     end      initialize("ak")     greet("aks") 

but getting error like:

argumenterror: wrong number of arguments calling `initialize` (1 0) 

i don't understand asking here, if argument why error (1 0). can me understand problem.

look @ code:

class person   attr_reader :name    def initialize( name )     puts "initializing person instance #{object_id}"     @name = name   end    def greet( name )     puts "hi #{name}, i'm #{name()}"   end end 

when wrote initialize without explicit receiver:

initialize( "ak" ) 

it matter of luck message recognized. has responded:

method( :initialize ).owner #=> basicobject 

basicobject, foremother of object instances, herself responded call, scolding wrong number of arguments, because:

method( :initialize ).arity #=> 0 

not method not expect arguments, not expected call @ all. in fact, not expected call #initialize on object yourself, save exceptional situations. class#new method handles calling of person#initialize method you:

a = person.new( 'abhinay' ) initializing person instance -605867998  #=> #<person:0xb7c66044 @name="abhinay"> 

person.new handled creation of new instance , automatically called #initialize method. also, #initialize method created private, if did not specify explitcitly. technical term such irregular behavior magic. person#initialize magically private:

a.initialize( 'fred' ) nomethoderror: private method `initialize' called #<person:0xb7c66044 @name="abhinay"> 

you cannot reinitialize 'fred', know. other methods public unless prescribed otherwise:

a.greet "arup" hi arup, i'm abhinay #=> nil 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -