Detailed analysis of variable _ruby topics in Ruby

Source: Internet
Author: User
Tags hash

Variable holds the location where the data for the program to be used is stored.

There are five types of variables supported by Ruby. A brief description and these variables have been experienced in the previous chapters. These five types of variables are described in this chapter.
Global Variables for Ruby:

Global variables begin with $. The value of the uninitialized global variable is zero and a warning is generated using the-w option.

The assignment of global variables changes the global state. It is not recommended to use global variables. They make the meaning of the program vague.

Here is an example showing 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, a hash number (#) character is able to access its value before any variable or constant.

Global variable in CLASS1 is 10
Global variable in CLASS2 is 10

Instance variables for Ruby:

Instance variable @ start. Uninitialized instance variables have a value of zero and produce a warning-w option.

The following is an example showing 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

# Create Objects
cust1=customer.new (' 1 ', ' John "," Wisdom apartments, Ludhiya ")
cust2=customer.new (" 2 "," Poul "," New Empire Road, Khandala ")

# Call Methods
cust1.display_details ()
cust2.display_details ()

The @cust_id here, @cust_name and @cust_addr are all 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's class variables:

Class variables start with @@ 开始 which can be used to initialize a method before it is defined.

A reference to an uninitialized class variable caused an error. The descendants of a class or module in which the class variable definition is shared between class variables.

Overwrite class variable produces warning-w option.

Here is an example showing 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 Objects
cust1=customer.new ("1", "John", "Wisdom apartments, Ludhiya")
cust2=customer.new ("2", "Poul", "New Empire Road, Khandala ")

# call Methods
cust1.total_no_of_customers ()
cust2.total_no_of_customers ()

@ @no_of_customers is a class of variables. This will produce the following results:

Total number of customers:1 total number of
Customers:2

Local Variables for Ruby:

Local variables begin with lowercase letters or _. A local variable is scoped to the range class, module, Def or do the corresponding end or block the left curly brace of the closing brace {}.

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

Allocation of uninitialized local variables is also declared as a variable. The variable begins to exist until the end of the current range arrives. The life cycle of a local variable is determined by Ruby parsing the program.

In addition, in the above example, the local variable ID, name and his addr.
Ruby constants:

Constants begin with uppercase letters. Constants defined in a class or module can be accessed in the class or module, and a class or module defined outside it is accessible globally.

Constants cannot be defined within a method. Referencing an uninitialized constant can result in an error. Assigning an initialized constant can produce 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 Objects
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

The pseudo variable of Ruby:

They are special variables, local variables, but look like constants. However, you cannot assign these variables to any value.

    • Self: The recipient object for the current method.
    • True: Represents a true value.
    • False: Represents a false value.
    • Nil: Represents a value that is not defined (undefined).
    • __FILE__: The name of the current source file.
    • __LINE__: The current line number in the source file.

The basic constant of Ruby:

Ruby's rules for using literals are simple and intuitive. This section describes all of the basic Ruby's constant values.
Number of integers:

Ruby supports integers. The range of integers from 230 to 230-1 or -262 to 262-1 in this range is an object of the Fixnum class, an integer outside this range stored in the Bignum class object.

Write an integer using an optional preamble, an optional cardinality representation (08, 0x for hexadecimal or binary 0b), followed by a string of digits in the corresponding cardinality. The number string to which the underline character is ignored.

For example:

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 # Bignum

Note: Classes and objects are explained in another chapter in this tutorial.
Floating point numbers:

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

For example:

123.4        # floating point value
1.0e6        # scientific notation
4E20         # dot not required
4e+20        # Sign before exponential

string literal values:

Ruby strings are simple 8-bit byte sequences that are objects of the string class. Double quote strings can override and backslash symbols, but do not allow single quotes to replace and allow only backslashes \ \ and \

For example:

#!/usr/bin/ruby-w

puts ' escape using ' \ ';
Puts ' that\ ' s right ';

This will produce the following results:

Escape using "\" That's right


can also be replaced with a string that represents the value of any Ruby expression using the #{expr} sequence. Expression 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 description:

The following is a list of backslash symbols supported by Ruby:

Ruby string For more details, please pass the Ruby string.
Ruby Arrays:

Ruby's array is a series of literal literals separated by a comma between the brackets that reference the drop object. The comma end is ignored.
For example:

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

Ruby's array of more details, passed through a ruby array.
Ruby Hash:

Literally Ruby creates a hash that places parentheses between the key/value pairs list, with a comma or sequence => between the keys and values. The comma end is ignored.
For 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,
red is 3840
Blue is 15

For a more detailed ruby hash, pass the ruby hash.
Ruby's scope:

The interval represented by the range. The start and end values of a group. May be used by S.. E and s...e text, or have a range.new range.

Range use. Contains running from start to finish. Create use ... Excludes final values. When used as an iterator, each value in the range sequence is returned.

Range (1..5) indicates that it includes the 1,2,3,4,5 value, range (1...5), which includes 1,2,3,4 four values.
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.