Examples of five variables in Ruby

Time:2019-11-12

Ruby global variables

Global variables start with $. The value of the uninitialized global variable is nil, which generates a warning when the – W option is used.

Assigning a global variable changes the global state, so it is not recommended to use a global variable.

The following example shows the use of global variables.


#!/usr/bin/ruby
 
$global_variable = 10
class Class1
 def print_global
   puts "Global variable in Class1 is #$global_variable"
 end
end
class Class2
 def print_global
   puts "Global variable in Class2 is #$global_variable"
 end
end
 
class1obj = Class1.new
class1obj.print_global
class2obj = Class2.new
class2obj.print_global

Here, $global “variable is a global variable. This will produce the following results:

Note: in ruby, you can access the value of any variable or constant by placing a ා character in front of it.


Global variable in Class1 is 10
Global variable in Class2 is 10

Ruby instance variable

Instance variables start with @. The value of the uninitialized instance variable is nil, which generates a warning when the – W option is used.

The following example shows the usage of the instance variable.

#!/usr/bin/ruby
 
class Customer
  def initialize(id, name, addr)
   @cust_id=id
   @cust_name=name
   @cust_addr=addr
  end
  def display_details()
   puts "Customer id #@cust_id"
   puts "Customer name #@cust_name"
   puts "Customer address #@cust_addr"
  end
end
 
#Create objects
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")
 
#Call method
cust1.display_details()
cust2.display_details()

Here, @ cust UU ID, @ cust UU name and @ cust UU addr are instance variables. This will produce the following results:


Customer id 1
Customer name John
Customer address Wisdom Apartments, Ludhiya
Customer id 2
Customer name Poul
Customer address New Empire road, Khandala

Ruby class variable

Class variables start with @ @, and must be initialized before they can be used in method definitions.

Referencing an uninitialized class variable can cause an error. Class variables can be shared in subclasses or submodules of the classes or modules that define them.

Overloading a class variable produces a warning when the – W option is used.

The following example shows the use of class variables.

#!/usr/bin/ruby
 
class Customer
  @@no_of_customers=0
  def initialize(id, name, addr)
   @cust_id=id
   @cust_name=name
   @cust_addr=addr
  end
  def display_details()
   puts "Customer id #@cust_id"
   puts "Customer name #@cust_name"
   puts "Customer address #@cust_addr"
  end
  def total_no_of_customers()
    @@no_of_customers += 1
    puts "Total number of customers: #@@no_of_customers"
  end
end
 
#Create objects
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")
 
#Call method
cust1.total_no_of_customers()
cust2.total_no_of_customers()

In this case, @ @ no’of’customers is a class variable. This will produce the following results:


Total number of customers: 1
Total number of customers: 2

Ruby local variables

Local variables begin with a lowercase letter or underscore. The scope of a local variable is from class, module, def, or do to the corresponding end or from the left brace to the right brace {}.

When an uninitialized local variable is called, it is interpreted as calling a method without parameters.

An uninitialized local variable assignment can also be treated as a variable declaration. The variable remains until the end of the current domain. The life cycle of local variables is determined at Ruby parser time.

In the above example, the local variables are ID, name, and addr.
Ruby constant

Constants start with an uppercase letter. Constants defined within a class or module can be accessed from within the class or module, and constants defined outside the class or module can be accessed globally.

A constant cannot be defined within a method. Referencing an uninitialized constant can produce an error. Assigning a value to a constant that has already been initialized generates a warning.

#!/usr/bin/ruby
 
class Example
  VAR1 = 100
  VAR2 = 200
  def show
    puts "Value of first Constant is #{VAR1}"
    puts "Value of second Constant is #{VAR2}"
  end
end
 
#Create objects
object=Example.new()
object.show

Here, VAR1 and var2 are constants. This will produce the following results:


Value of first Constant is 100
Value of second Constant is 200

Ruby pseudo variable

They are special variables that have the appearance of local variables but behave like constants. You cannot assign any value to these variables.

Self: the receiver object of the current method.
True: a value that represents true.
False: the value representing false.
Nil: the value representing undefined.
File: the name of the current source file.
Line: the number of the current line in the source file.

Ruby basic text

Ruby’s rules for writing are simple and intuitive. This part explains all the basic words in ruby.
integer

Ruby supports integers. The integer range is – 230 to 230-1 or – 262 to 262-1. Integers in this range are fixnum like objects, and integers outside this range are stored in bignum like objects.

You can use an optional leading symbol before an integer, an optional basic indicator (0 for octal, 0x for hex, 0b for binary), followed by a string of numbers. The underscore character is ignored in the number string.

You can get an ASCII character or an integer value of an escape sequence marked with a question mark.

Example:

123 × fixnum decimal
1 × fixnum underlined decimal
-500 × negative fixnum
0377 octal
0xff hex
0b1011 binary
Character code of "a" × "a"
? \ n ා encoding of newline character (0x0a)
12345678901234567890 # Bignum

Note: classes and objects are covered in a separate section of this tutorial.
Floating point number

Ruby supports floating-point numbers. They are numbers with decimals. Floating point numbers are float like objects and can be any of the following.

Example:

123.4 floating point value
1.0e6 scientific notation
4e20 is not required
Symbol before 4E + 20 ා index

String text

Ruby strings are simply an 8-bit byte sequence. They are string like objects. Double quotation mark strings are allowed to replace and use backslash symbols, single quotation mark strings are not allowed to replace, and only \ \ and \ ‘two backslash symbols are allowed.

Example:


#!/usr/bin/ruby -w
 
puts 'escape using "\"';
puts 'That\'s right';

This will produce the following results:


escape using "\"
That's right

You can use the sequence {expr} to replace the value of any Ruby expression with a string. Here, expr can be any Ruby expression.


#!/usr/bin/ruby -w
 
puts "Multiplication Value : #{24*60*60}";

This will produce the following results:


Multiplication Value : 86400

Backslash symbol

The following table lists the backslash symbols supported by Ruby:

2015410103359749.jpg (529×559)

Ruby array

Ruby arrays are a series of comma separated object references placed within square brackets. Trailing commas are ignored.
Example:


#!/usr/bin/ruby
 
ary = [ "fred", 10, 3.14, "This is a string", "last element", ]
ary.each do |i|
  puts i
end

This will produce the following results:


fred
10
3.14
This is a string
last element

To learn more about Ruby arrays, check out Ruby arrays.
Ruby hash

Ruby hashes are a series of key / value pairs placed within braces, separated by commas and sequences = > between keys and values. Trailing commas are ignored.
Example:


#!/usr/bin/ruby
 
hsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }
hsh.each do |key, value|
  print key, " is ", value, "\n"
end

This will produce the following results:


green is 240
red is 3840
blue is 15

Ruby range

A range represents a time interval. Ranges are represented by setting a start value and an end value. Ranges can be constructed using s.. E and s.. E, or by range.new.

The range constructed with.. runs from the start value to the end value (including the end value). The range constructed with… Runs from the start value to the end value (excluding the end value). When used as an iterator, the scope returns each value in the sequence.

Range (1.. 5) means it contains values 1, 2, 3, 4, 5, and range (1… 5) means it contains values 1, 2, 3, 4.
Example:


#!/usr/bin/ruby
 
(10..15).each do |n|
  print n, ' '
end

This will produce the following results:


10 11 12 13 14 15

Recommended Today

Custom factory class

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace LYZB.ApiConfig { /// ///Custom factory class /// // generic public abstract class AssesUtil where T : class,new() { /// ///Cache collection /// private static Hashtable hash = Hashtable.Synchronized(new Hashtable()); /// ///Execution instance method /// ///Method name ///Parameter type ///Parameter entity /// public […]