Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

264
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!