ArgumentError: invalid number of arguments in Ruby

Trying to solve this problem,

  class Person
      def initialize(name)
        @name=name
      end

      def greet(other_name)
       puts "Hi #{other_name}, my name is #{name}"
      end
    end

    initialize("ak")
    greet("aks")

but I get the error:

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

I don’t understand what is being asked here, if this is just an argument, then why the error is similar to (1 for 0). can someone help me understand this problem.

+4
source share
4 answers

Take a look at this 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 you wrote initializewithout an explicit recipient:

initialize( "ak" )

It was only lucky that your message was recognized. See who answered:

method( :initialize ).owner
#=> BasicObject

BasicObject, the nickname of all instances Object, she answered your call herself, scolding you for the wrong number of arguments, because:

method( :initialize ).arity
#=> 0

, . , #initialize , . Class#new Person#initialize :

A = Person.new( 'Abhinay' )
Initializing Person instance -605867998 
#=> #<Person:0xb7c66044 @name="Abhinay">

Person.new #initialize. , #initialize , . magic. Person#initialize :

A.initialize( 'Fred' )
NoMethodError: private method `initialize' called for #<Person:0xb7c66044 @name="Abhinay">

"", . , :

A.greet "Arup"
Hi Arup, I'm Abhinay
#=> nil
+8

( ), :

p = Person.new("ak")
p.greet("aks")          #=> "Hi aks, my name is ak"
+4

The problem is that to create a new object you need to call the method newfor the class, not initializefor the object.

So the code is as follows:

p = Person.new("John")
+3
source

Please take a look at the code below:

class Person
  attr_reader :name

  def initialize(name)
    @name = name
  end

  def greet(other_name)
    puts "Hi #{other_name}, my name is #{name}"
  end
end

person = Person.new("ak")
person.greet("aks")

#=> Hi aks, my name is ak
+1
source

Source: https://habr.com/ru/post/1530926/


All Articles