Five variables in Ruby and five types of ruby

Source: Internet
Author: User

Five variables in Ruby and five types of ruby

Ruby global variables

The global variable starts with $. If the value of the uninitialized global variable is nil, a warning is generated after the-w option is used.

Assigning a value to a global variable changes the global state. Therefore, we do not recommend that you use global variables.

The following example shows the usage of 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" endend class1obj = Class1.newclass1obj.print_globalclass2obj = Class2.newclass2obj.print_global

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

Note: In Ruby, you can place the # character before a variable or constant to access the value of any variable or constant.

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

Ruby instance variables

The instance variable starts. If the value of the uninitialized instance variable is nil, a warning is generated after the-w option is used.

The following example shows the usage of instance variables.

#! /Usr/bin/ruby class Customer def initialize (id, name, addr) @ cust_id = id @ cust_name = name @ cust_addr = addr end displaydef _details () puts "Customer id # @ cust_id" puts "Customer name # @ cust_name" puts "Customer address # @ cust_addr" endend # create object 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_id, @ cust_name, and @ cust_addr are 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 Variables

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

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

When the-w option is used, a warning is generated when the class variable is overloaded.

The following example shows the usage of class variables.

#! /Usr/bin/ruby class Customer @ no_of_mers MERs = 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_mers MERs () @ no_of_mers MERs + = 1 puts "Total number of MERs: # @ no_of_customers" endend # 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_mers MERs () cust2.total _ no_of_mers MERs ()

Here, @ no_of_mers Mers is a class 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 underscores. The scope of a local variable ranges from class, module, def, Or do to the end of the corresponding variable or from left braces to right braces {}.

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

You can assign values to uninitialized local variables as variable declarations. The variable will exist until the end of the current domain. The lifecycle of local variables is determined during Ruby parsing.

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

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

Constants cannot be defined in methods. Referencing an uninitialized constant produces an error. A warning is triggered when you assign values to initialized constants.

#! /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 }" endend # create object = 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 that have the appearance of local variables, but act like constants. You cannot assign any value to these variables.

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

Basic Ruby text

Ruby rules for text are simple and intuitive. This part explains all the basic text in Ruby.
Integer

Ruby supports integers. The integer ranges from-230 to 230-1 or-262 to 262-1. Integers in this range are Fixnum-like objects, and integers out of this range are stored in Bignum-like objects.

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

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

Instance:

123 # Fixnum decimal 1_234 # Fixnum underlined Decimal-500 # negative Fixnum0377 # octal 0xff # hexadecimal 0b1011 # binary? A # 'A' character encoding? \ N # linefeed (0x0a) encoding 12345678901234567890 # Bignum

Note: classes and objects are described in a separate chapter in this tutorial.
Floating Point Number

Ruby supports floating point numbers. They are decimal numbers. A floating point is a Float-like object and can be any of the following.

Instance:

123.4 # floating point value 1.0e6 # scientific note 4E20 # Not required 4e + 20 # symbol before Exponent

String text

The Ruby String is simply an 8-bit byte sequence, which is a String-like object. Strings marked with double quotation marks can be replaced with and use the backslash symbol. Strings marked with single quotation marks cannot be replaced, and only the backslash symbols \ and \ 'can be used.

Instance:

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

This produces the following results:

escape using "\"That's right

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

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

This produces the following results:

Multiplication Value : 86400

Backslash

The following table lists the backslash symbols supported by Ruby:

Ruby Array

A Ruby array contains a series of comma-separated object references in square brackets. The comma at the end is ignored.
Instance:

#!/usr/bin/ruby ary = [ "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

For more information about Ruby arrays, see Ruby arrays ).
Ruby hash

Ruby hashing stores a series of key/value pairs in braces, which are separated by commas and sequence =>. The comma at the end is ignored.
Instance:

#!/usr/bin/ruby hsh = 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

Ruby Scope

A range indicates a time interval. The range is expressed by setting a start value and an end value. The Range can be constructed using s. e and s. e, or by Range. new.

The range constructed using .. ranges from the start value to the end value (including the end value ). The range constructed using... ranges from the start value to the end value (excluding the end value ). When used as an iterator, the range returns each value in the sequence.

Range (1 .. 5) means it contains values 1, 2, 3, 4, 5, range (1... 5) it contains values 1, 2, 3, and 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.