Parse Ruby variables in detail, and parse Ruby variables in detail

Source: Internet
Author: User

Parse Ruby variables in detail, and parse Ruby variables in detail

The location where the variable holds the data of the program to be used.

Ruby supports five types of variables. In the previous section, we have gone through a brief description and these variables. These five types of variables are described in this chapter.
Ruby global variables:

The global variable starts with $. The value of the uninitialized global variable is zero, and the-w option is used to generate a warning.

The value assignment of global variables changes the global state. Global variables are not recommended. They blur the meaning of the program.

The following example shows how to use global variables.

#!/usr/bin/ruby$global_variable = 10class Class1 def print_global   puts "Global variable in Class1 is #$global_variable" endendclass Class2 def print_global   puts "Global variable in Class2 is #$global_variable" endendclass1obj = Class1.newclass1obj.print_globalclass2obj = Class2.newclass2obj.print_global

$ Global_variable is a global variable. This produces the following results:

Note: In Ruby, a hash (#) character can be used to access its value before any variable or constant.

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

Ruby instance variables:

Instance variable @ start. The value of uninitialized instance variables is zero and the warning-w option is generated.

The following example shows how to use instance variables.

#!/usr/bin/rubyclass 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"  endend# Create Objectscust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")cust2=Customer.new("2", "Poul", "New Empire road, Khandala")# Call Methodscust1.display_details()cust2.display_details()

Here, @ cust_id, @ cust_name and @ cust_addr are both instance variables. This produces the following results:

Customer id 1Customer name JohnCustomer address Wisdom Apartments, LudhiyaCustomer id 2Customer name PoulCustomer address New Empire road, Khandala

Ruby class variables:

Class variables start with @. They can be used to initialize before the method is defined.

An error occurred when Referencing uninitialized class variables. Class variables share the future of the class or module defined by the class variables.

Override the class variable to generate the warning-w option.

The following example shows how to use class variables:

#!/usr/bin/rubyclass 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"  endend# Create Objectscust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")cust2=Customer.new("2", "Poul", "New Empire road, Khandala")# Call Methodscust1.total_no_of_customers()cust2.total_no_of_customers()

@ No_of_mers Mers is a type of variable. This produces the following results:

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

Ruby local variables:

Local variables start with lowercase letters or. The range class of a local variable, module, def, or Close Brackets {} corresponding to the ending or left curly braces of the block {}.

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

Allocating uninitialized local variables is also declared as variables. The variable starts to exist until it reaches the end of the current range. The lifecycle of local variables can be determined only when Ruby parses the program.

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

A constant starts with an uppercase letter. Constants defined in a class or module can be accessed in this class or module, and a class or module can be accessed globally.

Constants cannot be defined in methods. Referencing uninitialized constants produces an error. Assign a constant initialized generates a warning.

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

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

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

Ruby pseudo variables:

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

  • Self: the receiver object of the current method.
  • True: indicates the true value.
  • False: indicates a false value.
  • Nil: undefined value.
  • _ FILE __: name of the current source FILE.
  • _ LINE __: current row number in the source file.

Basic common values of Ruby:

The rules for Ruby to use the literal value are simple and intuitive. This section describes the common values of all basic Ruby statements.
Integer:

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

An integer is written with an optional leading symbol. An optional base symbol (0 octal, 0x indicates hexadecimal or binary 0b), followed by a string of numbers in the base. Number string that is ignored by the underline character.

For example:

123         # Fixnum decimal1_234        # Fixnum decimal with underline-500         # Negative Fixnum0377         # octal0xff         # hexadecimal0b1011        # 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:

Ruby supports integers. They are numbers but decimal digits. A floating point is a Float object. It can be any of the following:

For example:

123.4        # floating point value1.0e6        # scientific notation4E20         # dot not required4e+20        # sign before exponential

String common value:

Ruby strings are simple 8-byte sequences, which are the objects of the String class. Double quotation mark strings can be replaced with backslash characters, but they cannot be replaced with single quotation marks or only backslash symbols \ and \'

For example:

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

This produces the following results:

escape using "\"That's right

You can also replace it with a string that uses the # {expr} sequence to represent the value of any Ruby expression. The expression expr can be any Ruby expression.

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

This produces the following results:

Multiplication Value : 86400

Backslash symbol description:

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

For more information about the Ruby string, see the Ruby string.
Ruby array:

Ruby arrays are a series of words separated by commas (,) between the square brackets that place object references. The end of the comma is ignored.
For example:

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

This produces the following results:

fred103.14This is a stringlast element

More details about the Ruby array are passed through the Ruby array.
Ruby hash:

Literally, Ruby creates a list of key/value pairs in a hash place between parentheses, using keys and values between commas or sequences =>. The end of the comma is ignored.
For example:

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

This produces the following results:

green is 240red is 3840blue is 15

For more detailed Ruby hashing, It is hashed by Ruby.
Ruby scope:

The interval represented by the range. The start and end values of a group. The Text s. e and s. e may be used, or the Range. new may exist.

Range use .. contains running from start to end. Create and use... to exclude the final value. As an iterator, each value in the range sequence is returned.

Range (1 .. 5) indicates that it includes values 1, 2, 3, 4, 5, range (1 .. 5) indicates that it includes values 1, 2, 3, 4.
Instance:

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

This produces 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.