Difference between various variables scopes in ruby - ruby

Ruby has 5 variable scopes:
Local Variables: these are the normal variables, example x = 25, y = gaurish where x and y are local variables.
Instance Variables: these are denoted with # symbol infront of the actual variable name. mainly used with classes, so that each instance/object of the class has a different/separate value. example. #employee.name = 'Alex'
Class Variables: denoted with ## symbols in front of variable name. class variable, I think have same value accos all instances/object.
Global variables: they start with $ symbol and are accessible everywhere. example $LOAD_PATH
Constants: Must start with Capital letter but by convention written in ALL_CAPS. although, it is a constant but its value its not constant and can be changed(ruby will throw a warning, though). so in the sense, this also acts like a variable.
As you may notice,all of the above are variables which store some value of some type and their value can be changed. But, each scope does something little bit different. Having 5 different types of variable scopes is confuses hell out of me. Mainly, I have difficulty deciding under what case, I should be using a particular scope in my code. so I have some questions in my mind. please answer:
I notice that local variables and class variables stay same for all objects/instances, unlike instance variables. so what difference between Local variables and Class variables?
Can local variables be used in place of class variables? or vice-versa. And if yes, then why, and if no, then why not?
Global variables in ruby remind me of the evil global $x variables in PHP. Are global variables in ruby also considered evil and therefore should not be used. OR, there are specific cases where it makes sense to use global variables in ruby?
Why constants are not constants and allow their value to be changed? A constant's value by definition should be constant right? else, we can just use another variable and don't change its value. would that be equivalent to a CONSTANT in ruby?
Any page/resource/link which explains the difference between 5 different variable scopes in ruby? I like to keep one handy for reference.
Under what use-case, I should be using a particular variable scope in my code. so one would explain all 5 cases with can example that would be cool, this is my main reason for confusion.
is there a de facto choice like public in java? Which would be the safe bet in most use-cases?
Thanks for taking time to read and answer question

Class variables are the same for all instances, because they're class variables–associated with the class. Everything access the same variable, including each instance.
No. Local variables are just that–local. They may be local to a function, or local to the class declaration, which is different than being a class variable. Locals in a class declaration go out of scope when the class declaration ends.
That's because they're exactly the same–they're global. Global state is always evil; this is not a property of the language or environment. That said, some global state may be required–that's just the way it is. It makes sense to use global state when there's global state. The trick is to use global state properly, which is sometimes a non-trivial endeavor.
That's just how Ruby is.
One has already been given by Chris.
I would think this question would be largely self-answering. Global when the entire world needs access. Instance when it's specific to a class instance. Local when it's only required in a local scope (e.g., a method, a block (note differences between 1.8 and 1.9 with regard to block scope), etc.) Constant when the variable isn't supposed to change. A class variable when it's something that either every instance needs, or if exposed via a class method, something tightly associated with a class.
There is no "most use-cases", it totally depends on what you're doing with the variable. And public isn't the de facto choice in Java–it depends on the entity in question. Default Java scope is package-private (methods, properties). Which to use in Ruby depends entirely upon the use-case, noting that as with Java, and even more easily in Ruby, things can be circumvented.

Local variables are not equivalent to class ones, they are tied to the block you are in. Any local declared in a block can be used there. Class variables are tied to the class structure you are in. Defining a class is itself a block, so you might be able to access local variables similarly, but you'll find if you refer to your class in a different context you cannot refer to the local variable in the same fashion.
Global variables are considered bad form, if abused. OOP should help you structure your programs such that constants on the entire program aren't needed. Think of them as actually being global: if you can't vouch for its consistency to the entire world, like the value of PI or whether or not you love your wife, you probably shouldn't be making promises.
Once you get the hang of them, I find "Ruby Variable Scope" to be a good reference.

I found a good and in-depth explanation regarding different scopes and their visibilities in Ruby in the following link .Scopes and Visibilities with Examples in detail.
According to it ,
Class variable (##a_variable): Available from the class definition and any sub-classes. Not available from anywhere outside.
Instance variable (#a_variable): Available only within a specific object, across all methods in a class instance. Not available directly from class definitions.
Global variable ($a_variable): Available everywhere within your Ruby script.
Local variable (a_variable): It is available only in the particular method or block in ruby script.
Some more explanation regarding Instance variables is : You can access instance variables in any method of that particular class. While local variables can't be accessed outside of the method. Below is an example from ruby monk which explains this concept thoroughly.
class Item
def initialize(item_name, quantity)
#item_name = item_name
#quantity = quantity
end
def show
puts #item_name
puts #quantity
supplier = "Acme corp"
puts supplier
end
end
Item.new("tv",1).show
Here supplier is a local variable which can be accessed from show method only in our example.Just try to declare the supplier variable in the initialize method and printing it out in show method. It will give an error as undefined variable supplier.
i hope it helps. :)

Here is my two cents for this and is writing for c++/java/c# programmers:
A Ruby local/$Global variable is a bit like c++/java/c#'s local/Global variable.
A Ruby #instance variable it's like c++/java/c#'s member variable /class property which can be accessible in any member function/class method.Though Ruby instance can be applied not only to class but also to Ruby Module.
A Ruby ##class variable is like as c++/java's static member variable which is share between all instances of the same class.

Related

using the ## with instance variables in ruby [duplicate]

Ruby has 5 variable scopes:
Local Variables: these are the normal variables, example x = 25, y = gaurish where x and y are local variables.
Instance Variables: these are denoted with # symbol infront of the actual variable name. mainly used with classes, so that each instance/object of the class has a different/separate value. example. #employee.name = 'Alex'
Class Variables: denoted with ## symbols in front of variable name. class variable, I think have same value accos all instances/object.
Global variables: they start with $ symbol and are accessible everywhere. example $LOAD_PATH
Constants: Must start with Capital letter but by convention written in ALL_CAPS. although, it is a constant but its value its not constant and can be changed(ruby will throw a warning, though). so in the sense, this also acts like a variable.
As you may notice,all of the above are variables which store some value of some type and their value can be changed. But, each scope does something little bit different. Having 5 different types of variable scopes is confuses hell out of me. Mainly, I have difficulty deciding under what case, I should be using a particular scope in my code. so I have some questions in my mind. please answer:
I notice that local variables and class variables stay same for all objects/instances, unlike instance variables. so what difference between Local variables and Class variables?
Can local variables be used in place of class variables? or vice-versa. And if yes, then why, and if no, then why not?
Global variables in ruby remind me of the evil global $x variables in PHP. Are global variables in ruby also considered evil and therefore should not be used. OR, there are specific cases where it makes sense to use global variables in ruby?
Why constants are not constants and allow their value to be changed? A constant's value by definition should be constant right? else, we can just use another variable and don't change its value. would that be equivalent to a CONSTANT in ruby?
Any page/resource/link which explains the difference between 5 different variable scopes in ruby? I like to keep one handy for reference.
Under what use-case, I should be using a particular variable scope in my code. so one would explain all 5 cases with can example that would be cool, this is my main reason for confusion.
is there a de facto choice like public in java? Which would be the safe bet in most use-cases?
Thanks for taking time to read and answer question
Class variables are the same for all instances, because they're class variables–associated with the class. Everything access the same variable, including each instance.
No. Local variables are just that–local. They may be local to a function, or local to the class declaration, which is different than being a class variable. Locals in a class declaration go out of scope when the class declaration ends.
That's because they're exactly the same–they're global. Global state is always evil; this is not a property of the language or environment. That said, some global state may be required–that's just the way it is. It makes sense to use global state when there's global state. The trick is to use global state properly, which is sometimes a non-trivial endeavor.
That's just how Ruby is.
One has already been given by Chris.
I would think this question would be largely self-answering. Global when the entire world needs access. Instance when it's specific to a class instance. Local when it's only required in a local scope (e.g., a method, a block (note differences between 1.8 and 1.9 with regard to block scope), etc.) Constant when the variable isn't supposed to change. A class variable when it's something that either every instance needs, or if exposed via a class method, something tightly associated with a class.
There is no "most use-cases", it totally depends on what you're doing with the variable. And public isn't the de facto choice in Java–it depends on the entity in question. Default Java scope is package-private (methods, properties). Which to use in Ruby depends entirely upon the use-case, noting that as with Java, and even more easily in Ruby, things can be circumvented.
Local variables are not equivalent to class ones, they are tied to the block you are in. Any local declared in a block can be used there. Class variables are tied to the class structure you are in. Defining a class is itself a block, so you might be able to access local variables similarly, but you'll find if you refer to your class in a different context you cannot refer to the local variable in the same fashion.
Global variables are considered bad form, if abused. OOP should help you structure your programs such that constants on the entire program aren't needed. Think of them as actually being global: if you can't vouch for its consistency to the entire world, like the value of PI or whether or not you love your wife, you probably shouldn't be making promises.
Once you get the hang of them, I find "Ruby Variable Scope" to be a good reference.
I found a good and in-depth explanation regarding different scopes and their visibilities in Ruby in the following link .Scopes and Visibilities with Examples in detail.
According to it ,
Class variable (##a_variable): Available from the class definition and any sub-classes. Not available from anywhere outside.
Instance variable (#a_variable): Available only within a specific object, across all methods in a class instance. Not available directly from class definitions.
Global variable ($a_variable): Available everywhere within your Ruby script.
Local variable (a_variable): It is available only in the particular method or block in ruby script.
Some more explanation regarding Instance variables is : You can access instance variables in any method of that particular class. While local variables can't be accessed outside of the method. Below is an example from ruby monk which explains this concept thoroughly.
class Item
def initialize(item_name, quantity)
#item_name = item_name
#quantity = quantity
end
def show
puts #item_name
puts #quantity
supplier = "Acme corp"
puts supplier
end
end
Item.new("tv",1).show
Here supplier is a local variable which can be accessed from show method only in our example.Just try to declare the supplier variable in the initialize method and printing it out in show method. It will give an error as undefined variable supplier.
i hope it helps. :)
Here is my two cents for this and is writing for c++/java/c# programmers:
A Ruby local/$Global variable is a bit like c++/java/c#'s local/Global variable.
A Ruby #instance variable it's like c++/java/c#'s member variable /class property which can be accessible in any member function/class method.Though Ruby instance can be applied not only to class but also to Ruby Module.
A Ruby ##class variable is like as c++/java's static member variable which is share between all instances of the same class.

Ruby module variable accessor not working as expected

So I want a module with a variable and access methods.
My code looks something like this
module Certificates
module Defaults
class << self
attr_accessor :address
def get_defaults
address = "something"
make_root_cert
end
def make_root_cert
blub = address
# do somthing
end
end
end
I inspected it with pry.
The result is
Certificates::Defaults has methods called address and address=.
If I call address in the get_defaults method it returns "something" as expected
If I call it in make_root_cert it returns nil
I used this way of attr_accessor creation in another module and it worked fine. I hope I'm just misunderstanding the way ruby works and somebody can explain why this example doesn't work. Maybe using the implementation details of the ruby object model.
Jeremy is right.
My findings
This seems inconsistent to me.
If you use the expression "address" and the instance variable has not been set it returns the local variable
If the instance variable has been set and the local variable not it returns the instance variable.
If both have been set it returns the local variable.
On the other hand address="test" always sets the local variable.
In your get_defaults methods, address is a local variable. To use the setter, you have to type this:
self.address = "something"
That will properly call the address= method.
This rather confusing behavior occurs because the Ruby interpreter places local variable definition at a higher precedence than method calls. There is consistency here, but unless you know how it works in advance it can be hard to see clearly.
Given that so many things in Ruby are objects and method calls, it might be natural to assume that variable definition was some sort of a method called on something (like Kernel or main or the object in which it was defined or whatever) and that the resulting variable was some sort of object. If this was the case, you would guess that the interpreter would resolve name conflicts between variable definitions and other methods according to the rules of method lookup, and would only define a new variable if it didn't find a method with the same name as the potential variable definition first.
However, variable definition is not a method call, and variables are not objects. Instead, variables are just references to objects, and variable definition is something the interpreter keeps track of below the surface of the language. This is why Kernel.local_variables returns an array of symbols, and there's no way to get an array of some sort of local variable objects.
So, Ruby needs a special set of rules to handle name conflicts between variables and methods. Non-local variables have a special prefix denoting their scope ($, #, etc.) which fixes this, but not so for local variables. If Ruby required parens after methods, that would also address this problem, but we are given the luxury of not having to do that. To get the convenience of referencing local variables without a prefix and invoking methods without parens, the language just defaults to assuming you want the local variable whenever it's in scope. It could have been designed the other way, but then you would have weird situations where you defined a local variable and it was instantly eclipsed by some faraway method with the same name halfway across the program, so it's probably better like this.
The Ruby Programming Language, p. 88, has this to say:
"...local variables don't have a punctuation character as a prefix. This means that local variable references look just like method invocation expressions. If the Ruby interpreter
has seen an assignment to a local variable, it knows it is a variable and not a method, and it can return the value of the variable. If there has been no assignment, then Ruby treats the expression as a method invocation. If no method by that name exists, Ruby raises a NameError."
It goes on to explain why you were getting nil when calling address in make_root_cert:
"In general, therefor, attempting to use a local variable before it has been initialized results in an error. There is one quirk--a variable comes into existence when the Ruby interpreter sees an assignment expression for that variable. This is the case even if that assignment is not actually executed. A variable that exists but has not been assigned a value is given the default value nil. For example:
a = 0.0 if false # This assignment is never executed
print a # Prints nil: the variable exists but is not assigned
print b # NameError: no variable or method named b exists"
The setter method you get with attr_accessor leads the interpreter to create a variable before the setter method is ever called, but it has to be called to assign that variable a value other than nil. address = "something" in get_defaults defines a local variable within that method called address that goes out of scope at the end of the method. When you call make_root_cert, there's no local variable called address, so the getter method address that you got with attr_accessor is called and returns nil because the setter method hasn't been called to give it some other value. self.address= lets the interpreter know that you want the class method address= instead of a new local variable, resolving the ambiguity.

Using Instance Variables in Class Methods - Ruby

I have a class something like below, and I used instance variables (array) to avoid using lots of method parameters.
It works as I expected but is that a good practice?
Actually I wouldn't expect that worked, but I guess class methods are not working as static methods in other languages.
class DummyClass
def self.dummy_method1
#arr = []
# Play with that array
end
def self.dummy_method2
# use #arr for something else
end
end
The reason instance variables work on classes in Ruby is that Ruby classes are instances themselves (instances of class Class). Try it for yourself by inspecting DummyClass.class. There are no "static methods" in the C# sense in Ruby because every method is defined on (or inherited into) some instance and invoked on some instance. Accordingly, they can access whatever instance variables happen to be available on the callee.
Since DummyClass is an instance, it can have its own instance variables just fine. You can even access those instance variables so long as you have a reference to the class (which should be always because class names are constants). At any point, you would be able to call ::DummyClass.instance_variable_get(:#arr) and get the current value of that instance variable.
As for whether it's a good thing to do, it depends on the methods.
If #arr is logically the "state" of the instance/class DummyClass, then store it in instance variable. If #arr is only being used in dummy_method2 as an operational shortcut, then pass it as an argument. To give an example where the instance variable approach is used, consider ActiveRecord in Rails. It allows you to do this:
u = User.new
u.name = "foobar"
u.save
Here, the name that has been assigned to the user is data that is legitimately on the user. If, before the #save call, one were to ask "what is the name of the user at this point", you would answer "foobar". If you dig far enough into the internals (you'll dig very far and into a lot of metaprogramming, you'll find that they use instance variables for exactly this).
The example I've used contains two separate public invocations. To see a case where instance variables are still used despite only one call being made, look at the ActiveRecord implementation of #update_attributes. The method body is simply load(attributes, false) && save. Why does #save not get passed any arguments (like the new name) even though it is going to be in the body of save where something like UPDATE users SET name='foobar' WHERE id=1;? It's because stuff like the name is information that belongs on the instance.
Conversely, we can look at a case where instance variables would make no sense to use. Look at the implementation of #link_to_if, a method that accepts a boolean-ish argument (usually an expression in the source code) alongside arguments that are ordinarily accepted by #link_to such as the URL to link to. When the boolean condition is truthy, it needs to pass the rest of the arguments to #link_to and invoke it. It wouldn't make much sense to assign instance variables here because you would not say that the invoking context here (the renderer) contains that information in the instance. The renderer itself does not have a "URL to link to", and consequently, it should not be buried in an instance variable.
Those are class instance variables and are a perfectly legitimate things in ruby: classes are objects too (instances of Class) and so have instance variables.
One thing to look out for is that each subclass will have its own set of class instance variables (after all these are different objects): If you subclassed DummyClass, class methods on the subclass would not be able to see #arr.
Class variables (##foo) are of course the other way round: the entire class hierarchy shares the same class variables.

Which is better? Creating a instance variable or passing around a local variable in Ruby?

In general what is the best practice and pro/cons to creating an instance variable that can be accessed from multiple methods or creating an instance variable that is simply passed as an argument to those methods. Functionally they are equivalent since the methods are still able to do the work using the variable. While I could see a benefit if you were updating the variable and wanted to return the updated value but in my specific case the variable is never updated only read by each method to decide how to operate.
Example code to be clear:
class Test
#foo = "something"
def self.a
if #foo == "something"
puts "do #{#foo}"
end
end
a()
end
vs
class Test
foo = "something"
def self.a(foo)
if foo == "something"
puts "do #{foo}"
end
end
a(foo)
end
I don't pass instance variable around. They are state values for the instance.
Think of them as part of the DNA of that particular object, so they'll always be part of what makes the object be what it is. If I call a method of that object, it will already know how to access its own DNA and will do it internally, not through some parameter being passed in.
If I want to apply something that is foreign to the object, then I'll have to pass it in via the parameters.
As you mentioned, this is a non-functional issue about the code. With that in mind...
It's hard to give a definitive rule about it since it depends entirely on the context. Is the variable set once and forgotten about it, or constantly updated? How many methods share the same variable? How will the code be used?
In my experience, variables that drive behavior of the object but are seldom (if at all) modified are set in the initialize method, or given to the method that will cascade behavior. Libraries and leaf methods tend to have the variable passed in, as it's likely somebody will want to call it in isolation.
I'd suggest you start by passing everything first, and then refactoring if you notice the same variable being passed around all over the class.
If I need a variable that is scoped at the instance level, I use an instance variable, set in the initialize method.
If I need a variable that is scoped at the method level (that is, a value that is passed from one method to another method) I create the variable at the method level.
So the answer to your question is "When should my variable be in scope" and I can't really answer that without seeing all of your code and knowing what you plan to do with it.
If your object behavior should be statically set in the initialization phase, I would use an instance variable.

Constants or class variables in ruby?

I've been programming in Ruby for a few months now, and I'm wondering when it is appropriate to use constants over class variables and vice versa. (I'm working in Rails, thinking about constants in models).
class Category
TYPES = %w(listing event business).freeze
end
OR
class Category
##types = %w(listing event business).freeze
cattr_reader :types
end
Are there circumstances where one is preferable to another? Or is it just a matter of taste/style?
The main thing is that by using the CONSTANT notation, you're making it clear to the reader. the lower case, frozen string gives the impression is might be settable, forcing someone to go back and read the RDoc.
If these are really constant values that you define in source code and do not want to change during code execution then I would recommend to use constant.
If you plan to set and/or change these values dynamically during execution then use class variable with getters and setters.
Basically, you could put it like this: If you want something that's constant, use a constant. If you want something that's variable, use a variable. It seems like your list of types are constants, seeing it is a frozen array, so I would say it makes sense to use a constant in this case.
Note that class variables are private to a class and its instances (cf. http://phrogz.net/programmingruby/tut_classes.html). However, if you want to make your constant private you can always do:
FOO = 18
private_constant :FOO
If you don't want the value to ever change during the runtime of your program, and you are comfortable with allowing the value to be accessed outside of your class, use a constant.
Otherwise, you can use a class variable. However, be aware that class variables are shared among subclasses and instances of subclasses. So if you might at some point in the future implement a child class, you have to be very careful about your use of class variables.
Refer to the answers here for more on this: Class variables in Ruby

Resources