Example of five variables _ruby topics in Ruby

Source: Internet
Author: User
Tags constant time interval

Ruby Global Variables

Global variables begin with $. The value of an uninitialized global variable is nil, and a warning is generated when the-w option is used.

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

The following example shows the use of global variables.

#!/usr/bin/ruby
 
$global _variable = ten
class Class1
 def print_global
   puts "global variable in CLASS1 is # $global _variable "End of
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 values of any variable or constant by placing a # character in front of the variable or constant.

Global variable in CLASS1 's
global variable in CLASS2 is 10

Ruby instance variables

The instance variable begins with the @. The value of an uninitialized instance variable is nil, and a warning is generated when the-w option is used.

The following example shows the use of instance variables.

#!/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
 
# # to create Objects
cust1=customer.new ("1", "John", " Wisdom apartments, Ludhiya ")
cust2=customer.new (" 2 "," Poul "," New Empire Road, Khandala ")
 
# Calling Method
Cust1.display_details ()
cust2.display_details ()

Here, @cust_id, @cust_name, and @cust_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 n Ame Poul
Customer address New Empire Road, Khandala

Ruby class variables

A class variable begins with @@ 开头 must be initialized before it can be used in a method definition.

Referencing an uninitialized class variable can produce an error. A class variable can be shared in a subclass or child module of a class or module that defines it.

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
 
# Create Object
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, the @ @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 the local variable is from the class, module, Def or do to the end of the corresponding or from the opening brace to the closing brace {}.

When an uninitialized local variable is invoked, it is interpreted as invoking a method with no parameters.

Assignment of uninitialized local variables can also be treated as variable declarations. The variable persists until the current domain ends. The life cycle of a local variable is determined when the Ruby resolver is in process.

In the above example, the local variable is ID, name, and addr.
Ruby Constants

Constants begin with uppercase letters. Constants defined within a class or module can be accessed from within a class or module, and constants defined outside a class or module can be accessed globally.

Constants cannot be defined within a method. Referencing an uninitialized constant results in an error. Assigning a value to a constant that has already been initialized produces a warning.

#!/usr/bin/ruby
 
class Example
  VAR1 =
  VAR2 = def show
    puts "Value of the ' a ' of the ' of the ' of the ' Constant} '
    puts ' Value of second Constant is #{var2} '
  end
 
# Create Object
object=example.new ()
Object.show

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

Value of a Constant is
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 values to these variables.

Self: The receiver object for the current method.
True: A value that represents true.
False: A value that represents false.
Nil: Represents the value of 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 section explains all the basic text in Ruby.
Integer

Ruby supports integers. Integers range from-230 to 230-1 or-262 to 262-1. Integers in this range are class Fixnum objects, and integers outside this range are stored in objects of class Bignum.

You can use an optional preamble before an integer, an optional basic metric (0 corresponds to the octal,0x corresponding to the hex,0b binary) followed by a string of digits. The underscore character is ignored in the numeric string.

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

Instance:

123         # fixnum decimal
1_234        # Fixnum with underlined decimal
-500         # negative Fixnum 0377         # octal
0xff         # hex c10/>0b1011        # binary
? A          # ' a ' character encoding
? \ n         # line feed (0x0a) encoding
12345678901234567890 # Bignum

Note: Classes and objects are explained in a separate section of this tutorial.
floating point numbers

Ruby supports floating-point numbers. They are numbers with decimals. A floating-point number is an object of class float and can be any of the following.

Instance:

123.4        # Floating-point value
1.0e6        # scientific notation
4E20         # not required
4e+20        # symbol before the index

String literals

A Ruby string is simply a 8-bit byte sequence, which is an object of the class string. The double quotation mark string allows the substitution and use of backslashes, the single quotation mark string is not allowed to be replaced, and only the \ and \ ' Two backslash symbols are allowed.

Instance:

#!/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

Anti-slash symbol

The following table lists the backslash symbols supported by Ruby:

Ruby Array

A Ruby array is a series of comma-delimited object references within square brackets. The trailing comma is ignored.
Instance:

#!/usr/bin/ruby
 
ary = ["Fred", 3.14, "This is a string", "last Element",] Ary.each do
|i|
  Puts I end

This will produce the following results:

Fred
3.14 This are
a string last
element

For more details on the ruby array, see the ruby array.
Ruby Hash

Ruby Hashes place a series of key/value pairs within curly braces, separated by commas and sequence => between keys and values. The trailing comma is ignored.
Instance:

#!/usr/bin/ruby
 
HSH = colors = {"Red" => 0xf00, "green" => 0x0f0, "Blue" => 0x00f}
Hsh.each do |key, VA lue|
  Print key, "is", value, "\ n" End

This will produce the following results:

Green is,
red is 3840
Blue is 15

Ruby Range

A range represents a time interval. The scope is represented by setting a start value and an end value. Range can be used with S.. E and s...e to construct, or to construct by Range.new.

Use.. The constructed range runs from the start value to the ending value (including the ending value). Use... The constructed range runs from the start value to the end value (not including the ending value). When used as an iterator, the scope returns each value in the sequence.

The range (1..5) means that it contains a value of 1, 2, 3, 4, 5, and the range (1...5) means that it contains a value of 1, 2, 3, 4.
Instance:

#!/usr/bin/ruby
 
(10..15). Each do |n|
  Print N, ' End

This will produce the following results:

10 11 12 13 14 15

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.