Ruby - Class methods

methods, ruby

Solution

During the execution of `Pessoa#initialize` `self` holds an instance of the class `Pessoa`. Therefore, you're trying to call `new` on an instance of the class `Pessoa`. This is impossible, because `new` is a instance method of class `Class`: you're correctly calling it on the `Pessoa` class in the last lines, but you can't call it on an instance (such as `pessoa1` or `pessoa2`, or the `self` in the `Pessoa#initialize` method), because none of them is a Class, and therefore don't define the `new` method.

The correct code would be:

class Pessoa
  attr_accessor :nome, :idade, :altura

  @@lista = []

  def self.lista
    @@lista
  end

  def initialize(nome, idade, altura)
    @nome = nome
    @idade = idade
    @altura = altura
    @@lista << self
  end
end

pessoa1 = Pessoa.new("Joao",13,2)
pessoa2 = Pessoa.new("Alfredo",15,1)
puts Pessoa.lista.inspect

Problem

I'm a newbie starting to learn Ruby. I have created this code, however it returns it keeps returning `NoMethodError, undefined method new`. What am i doing wrong here? ``` class Pessoa attr_accessor :nome, :idade, :altura @@lista = [] def self.lista @@lista end def initialize(nome, idade, altura) pessoa = self.new pessoa.nome = nome pessoa.idade = idade pessoa.altura = altura @@lista << self end end pessoa1 = Pessoa.new("Joao",13,2) pessoa2 = Pessoa.new("Alfredo",15,1) puts Pessoa.lista.inspect ```

Original source