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
During the execution of
Pessoa#initializeselfholds an instance of the classPessoa. Therefore, you’re trying to callnewon an instance of the classPessoa.This is impossible, because
newis a instance method of classClass: you’re correctly calling it on thePessoaclass in the last lines, but you can’t call it on an instance (such aspessoa1orpessoa2, or theselfin thePessoa#initializemethod), because none of them is a Class, and therefore don’t define thenewmethod.The correct code would be: