What’s the best practice for hiding variables in a Ruby file, like the equivalent of a (function() {})() closure in JavaScript?
So if I have a file:
foo = 5
bar = foo * foo
I only want to expose bar, not foo, when someone requires it.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you have a file containing those two lines and someone requires that file, neither of the two variables will be exposed. Local variables are still local to the file even if they appear at the global scope.
If you want to expose
bar, you’ll need to turn it into a global variable$baror, if you don’t intend for the variable to change, into a constantBar. By not doing the same thing tofooit will automatically not be exposed.You might also consider wrapping the whole thing up in a module or class.