In this article, we’re going to explore about * variable (integer, float, string, backslash notation, array, range, hash, global, constant, class, instance) * attribute
Integer
An integer number can range from -2³⁰ to 2³⁰–1 or -2⁶² to 2⁶²–1. Within this range are objects of class Fixnum and outside this range are stored in objects of class Bignum
You write integers using an optional leading sign, an optional base indicator (0 for octal, 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string
123 # Fixnum decimal 1_234 # Fixnum decimal with underline -500 # Negative Fixnum 0377 # octal 0xff # hexadecimal 0b1011 # binary ?a # character code for 'a' ?\n # code for a newline (0x0a) 12345678901234567890 # BignumFloating
Float
number with decimals
123.4 # floating point value 1.0e6 # 1,000,000 4e+9 # 4,000,000,000 4e-2 # 0.04
String
Double-quoted strings allow substitution and backslash notation but single-quoted strings don’t allow substitution and allow backslash notation only for \\ and \’
puts 'escape using "\\"' #=> escape using "\" puts 'That\'s right'; #=> that's rightputs "Multiplication Value : #{24*60*60}" #=> Multiplication Value : 86400
Backslash Notations
Array
Literals of Ruby Array are created by placing a comma-separated series of object references between the square brackets. A trailing comma is ignored
[ "fred", 10, 3.14, "This is a string", "last element", ]
There is no way to prevent a constant from changing because variables in Ruby are not containers, they are simply pointers to objects. The only way to make the constant immutable is to use freeze.
Can set value but can not define constant inside a method
constantizerails-method will convert astring into a CONSTANT(Class/Module/Constant). Be careful with this method, it could be biased to inject external code into your server (example)
module/class ConstantSample SAMPLE_CONST = 'sample' private_constant :SAMPLE_CONST endConstantSample.const_defined?(:NOT_EXISTING_CONST_SAMPLE) # => falseConstantSample::SAMPLE_CONST #=> NameError: private constant ConstantSample::SAMPLE_CONST referenced # override the error of constant missing of an Object def Object.const_missing(name) @looked_for ||= {} str_name = name.to_s raise "Class not found: #{name}" if @looked_for[str_name] @looked_for[str_name] = 1 file = str_name.downcase require file klass = const_get(name) return klass if klass raise "Class not found: #{name}" end
Class variable
Class variables begin with @@ and must be initialized before they can be called/used. Otherwise, when call to get the value, it would throw the exception
Can call getter/setter class variable by methods * [class].class_variable_set(:@@var, ‘class variable 01’) * [class].class_variable_get(:@@var) * def self.set_var(str); @@var = ‘class variable 02’ ; end * def self.get_var(str); @@var ; end
be careful when using get/set directly by @@var , because all the variables in ruby are objects and the variable class can be accidentally bound to a specific class variable of an ancestor (Module/Class). Please find a sample in class_variable_binding_to_a_module.rb and the way we can prevent it in class_variable_self_owner.rb
class variable can be shared when INCLUDEa module or INHERITfrom a class (an ancestor). Please find a sample in variable_class_when_extend.rb and variable_class_when_include.rb
Class Instance variable
“class instance variable” is module/class’s OWN property, NO sharing when the module/class includes/extends a module or inherits a class
getter/setter by methods * [class].instance_variable_set(:@ins_var, ‘instance var of class 01’) * [class].instance_variable_get(:@ins_var) * def self.class_instance_var_set(str); @ins_var = ‘instance var of class 01’; end * def self.class_instance_var_get; @ins_var; end
Instance variable
variable of instance that’s initialized from a class
class A def initialize(str) @a = str enddef a; @a; end def a=(str); @a = str; end endins = A.new('instance var 01') ins.a #=> instance var 01 ins.a = 'instance var 02' ins.a #=> instance var 02
attr/attr_reader
this method creates a lazy instance variable and initializes a get method for this instance’s attribute
attr_writer
this method creates a lazy instance variable and initializes a set method for this instance’s attribute
attr_accessor
this method creates a lazy instance variable and initializes a get, set method for this instance’s attribute
lazy variable
the lazy variable means the variable is only initialized when we set it a value
class_attribute (only in Rails)
it’s not the same as the instance’s attribute. it doesn’t define the class’s variable
this class attribute’s value would be inheritable by its descendants/subclasses. Descendants/Subclasses can change their own value and it will not impact the parent class variable
there are some options of this method * :instance_reader — Sets the instance reader method (defaults to true) * :instance_writer — Sets the instance writer method (defaults to true) * :instance_accessor — Sets both instance methods (defaults to true) * :instance_predicate — Sets a predicate method (defaults to true) * :default — Sets a default value for the attribute (defaults to nil)
as we can see, :instance_reader is equivalent to :attr_reader and so on
if the instance’s variable doesn’t set to a value yet, it uses the class attribute’s value
Thank you for your patience. I hope you can find something helpful in this post
passion in finding solutions and research some things relate to technical and helpful in life. Also strongly interest in foods, travel, and gentle music :)