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?
CodePudding user response:
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"
CodePudding user response:
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.