Ruby variables
From wikinotes
Scope
# local variables variable = "some string" # local variables lowercase variables, start [a-z_] _variable = "some other string" # global variables $variable = "I'm global" # global variables begin with '$' # objects @variable = "attached to my class-instance" # instance variable @@variable = "a class variable" # class variable # constants MY_VARIABLE = "test" # constants are marked by a capitalized first-letter My_Variable = "test" # ruby issues warning when a constant is reassigned to a new value.
Assignment
variable = "foo"
Environment Variables
ENV['HOSTNAME'] = "myhostname"
Type Conversion
2.to_f ## to Float 2.to_i ## to Integer (FixNum) 2.to_s ## to String
Object Introspection
# retrieve an object's class nil.class => NilClass self.inspect => main # get file object class was defined in self.__FILE__ # certain keywords allow you to get information # about the current namespace: methods # list of methods instance_variables # list of instance variables
Freezing Variables
You can freeze a variable, preventing other objects from accessing it (results in TypeError).
variable = Person("me") variable.freeze variable.rename("you") # raises TypeError
dup/clone (shallow copy, deep copy)
dup shallow copy, new instances of attributes? clone shallow copy, same instances of attributes?