Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

263
Visualizações
Variable exporting in Ruby

I am new to Ruby so could you please explain one thing to me. Here is my code file:

class You
  def method
    puts "are the best"
  end
end

CONST = "const value"
var = "var value"

I require it in another file or irb. After that, I can access all of declared names except var. As far as I understand, Ruby distinguishes constants from variables by writing in uppercase. But why aren't the variables exported?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

In fact, there are no top-level declarations in Ruby. All execution is performed in context of the Object class (which is also a base class for every class in Ruby), so every top-level declaration is also a private member of the Object class. Instance variables have at-sign prefix (@), so your variable var is not even an instance variable, it is just local, which is not accessible outside its scope. Besides, instance variables in Ruby are always private too.

Instead, you can make it an instance variable and define getter and (optionally) setter for it:

# file.rb
@var = "var value"

def var
  @var
end

def var=(val)
  @var = val
end

And then:

$ irb -r ./file.rb
irb(main):001:0> var
=> "var value"
irb(main):002:0> var = "another var value"
=> "another var value"
irb(main):003:0> var
=> "another var value"
over 4 years ago · Santiago Trujillo Relatório

0

Local variables aren't exported because that's how require is documented to work:

Any constants or globals within the loaded source file will be available in the calling program's global namespace. However, local variables will not be propagated to the loading environment.

Constants (including You in class You) and are globally scoped because that's generally what you want in the absence of an explicit exporting mechanism.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda