Access a hash/list in a class

Asked

Viewed 78 times

0

Hello.

I’m an intermediate student in python, and recently I started studying Ruby, but like all new language, there are some small difficulties.

My question is: Where is the error in this? I used the function has_key?() outside the class, and it worked perfectly, but within the class, from the following error:

`FuncLogin': undefined method `has_key?' for nil:NilClass (NoMethodError)

I am doing a simple program of login and account creation, but is giving this error. Follow the full code:

class User
attr_accessor :login, :password

@contas = {"admin" => "pass"}

def initialize(login, password)
    @login    = login
    @password = password
end

def FuncLogin
    if @contas.has_key?(@login)
        if contas[@login] == @password
            return "Logado"
        else
            puts "Senha incorreta."
        end
    else
        return "Login inexistente."
    end
end
end

1 answer

1

The problem is that you assign @contas within the scope of the class. In Ruby, scopes are very important.

See the following example:

class Carro
  attr_accessor :modelo, :ano

  def andar
    puts 'Estou andando...'
  end
end

That one attr_accessor is called the class scope as there is no defined instance. The def andar, is the same case. You define a method in the class, to be accessed by object instances.

To set the value of a field attr_accessor, you must do at instance level.

class Carro
  attr_accessor :modelo, :ano

  def initialize(modelo, ano)
    @modelo = modelo
    @ano = ano
  end

  def andar
    puts 'Estou andando...'
  end
end

The construction method, initialize can take care of it, since it is called at the instance level.

tesla = Carro.new 'Tesla Model 3', 2018
tesla.andar

Another point: always follow the conventions. For classes/modules, use PascalCase. For variables and methods, use snake_case_minusculo. This can cause you problems later, since in Ruby, every object declared with an uppercase initial, i.e., Abc or ABC, is a constant.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.