gqmonteiro
gqmonteiro

Reputation: 37

Ruby - Class methods

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

Upvotes: 3

Views: 2586

Answers (2)

Alberto Moriconi
Alberto Moriconi

Reputation: 1655

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

Upvotes: 7

Chuck
Chuck

Reputation: 237110

That pessoa = self.new is your problem. initialize is called on an object that's already been created to set up its initial state, so

  1. self doesn't have a new method there (because it isn't a class)

  2. There's no point in creating an object in there and assigning it to the local variable pessoa, because it will just disappear after the method is finished

I think what you want is:

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

Upvotes: 3

Related Questions