Ruby 简明教程

Ruby - Variables, Constants and Literals

变量是程序用来保存数据的内存位置。

Variables are the memory locations, which hold any data to be used by any program.

Ruby 支持五种类型的变量。在上一章你也已经简要地了解了这些变量。这五个类型的变量将在本节进行讲解。

There are five types of variables supported by Ruby. You already have gone through a small description of these variables in the previous chapter as well. These five types of variables are explained in this chapter.

Ruby Global Variables

全局变量以 $ 开头。未初始化的全局变量具有 nil 值,并且使用 -w 选项会产生警告。

Global variables begin with $. Uninitialized global variables have the value nil and produce warnings with the -w option.

对全局变量进行赋值会改变全局状态。不建议使用全局变量,它们会让程序晦涩难懂。

Assignment to global variables alters the global status. It is not recommended to use global variables. They make programs cryptic.

这里有一个展示全局变量使用方式的示例。

Here is an example showing the usage of global variable.

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

这里 $global_variable 是一个全局变量。这会产生以下结果:

Here $global_variable is a global variable. This will produce the following result −

NOTE - 在 Ruby 中,你可以在变量或常量的前面加上井号字符(#)来访问该变量或常量的值。

NOTE − In Ruby, you CAN access value of any variable or constant by putting a hash (#) character just before that variable or constant.

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

Ruby Instance Variables

实例变量以 @ 开头。未初始化的实例变量具有 nil 值,并且使用 -w 选项会产生警告。

Instance variables begin with @. Uninitialized instance variables have the value nil and produce warnings with the -w option.

这里有一个展示实例变量使用方式的示例。

Here is an example showing 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
   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 Methods
cust1.display_details()
cust2.display_details()

这里,@cust_id、@cust_name 和 @cust_addr 是实例变量。这会产生以下结果:

Here, @cust_id, @cust_name and @cust_addr are instance variables. This will produce the following result −

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 Variables

类变量以 @@ 开头,并且必须在可以在方法定义中使用它们之前对其进行初始化。

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

引用未初始化的类变量会产生错误。类变量在定义了类变量的类或模块的后代中共享。

Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.

覆盖类变量会使用 -w 选项产生警告。

Overriding class variables produce warnings with the -w option.

这里有一个展示类变量使用方式的示例:

Here is an example showing the usage of class variable −

#!/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 Methods
cust1.total_no_of_customers()
cust2.total_no_of_customers()

此处 @@no_of_customers 是一个类变量。该类变量将生成以下结果:

Here @@no_of_customers is a class variable. This will produce the following result −

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

Ruby Local Variables

局部变量以小写字母或 _ 开头。局部变量作用域范围从类、模块、def 或 do 到相应的 end,或从代码块的花括号开头到结尾 {}。

Local variables begin with a lowercase letter or _. The scope of a local variable ranges from class, module, def, or do to the corresponding end or from a block’s opening brace to its close brace {}.

引用未初始化的局部变量时,将将其解释为一种对此方法的调用,此方法无参数。

When an uninitialized local variable is referenced, it is interpreted as a call to a method that has no arguments.

对未初始化局部变量的赋值还可用作变量声明。变量在当前作用域结束之前一直存在。在 Ruby 解析程序时确定局部变量的生命周期。

Assignment to uninitialized local variables also serves as variable declaration. The variables start to exist until the end of the current scope is reached. The lifetime of local variables is determined when Ruby parses the program.

在以上示例中,局部变量为 id、name 和 addr。

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

Ruby Constants

常量以大写字母开头。可以在定义它们所在类的模块内访问类或模块中定义的常量,也可以全局访问定义在类或模块外部的常量。

Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally.

不可在方法内定义常量。引用未初始化的常量将导致错误。对已初始化的常量进行赋值将产生警告。

Constants may not be defined within methods. Referencing an uninitialized constant produces an error. Making an assignment to a constant that is already initialized produces 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

此处 VAR1 和 VAR2 为常量。该类常量将生成以下结果:

Here VAR1 and VAR2 are constants. This will produce the following result −

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

Ruby Pseudo-Variables

它们是既表现为局部变量、又表现为常量形式的特殊变量。你无法为这些变量赋予任何值。

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

  1. self − The receiver object of the current method.

  2. true − Value representing true.

  3. false − Value representing false.

  4. nil − Value representing undefined.

  5. FILE − The name of the current source file.

  6. LINE − The current line number in the source file.

Ruby Basic Literals

Ruby 使用的文字规则简单直观。本节解释所有基本的 Ruby 文字。

The rules Ruby uses for literals are simple and intuitive. This section explains all basic Ruby Literals.

Integer Numbers

Ruby 支持整数。整数的范围可以从 -230 到 230-1 或从 -262 到 262-1。在此范围内的整数是 Fixnum 类的对象,而超出此范围的整数则存储在 Bignum 类的对象中。

Ruby supports integer numbers. An integer number can range from -230 to 230-1 or -262 to 262-1. Integers within this range are objects of class Fixnum and integers outside this range are stored in objects of class Bignum.

你可以使用可选的前置符号、可选的进制指示符(8 进制为 0,16 进制为 0x,2 进制为 0b),后跟用相应进制表示的一串数字来编写整数。连字符字符在数字字符串中将被忽略。

You write integers using an optional leading sign, an optional base indicator (0 for octal, 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string.

你还可以获取与 ASCII 字符对应的整数值,或通过使其前置一个问号来转义序列。

You can also get the integer value, corresponding to an ASCII character or escape the sequence by preceding it with a question mark.

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 − 本教程中的单独一章解释了类和对象。

NOTE − Class and Objects are explained in a separate chapter of this tutorial.

Floating Numbers

Ruby 支持浮点数。它们也是数字,但带有关数。浮点数字是 Float 类的对象,可以采用以下任何值 −

Ruby supports floating numbers. They are also numbers but with decimals. Floating-point numbers are objects of class Float and can be any of the following −

Example

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

String Literals

Ruby 字符串只是 8 位字节的序列,它们是 String 类的对象。双引号字符串允许替换和反斜杠表示法,但单引号字符串不允许替换,只允许对 \\ 和 \' 使用反斜杠表示法

Ruby strings are simply sequences of 8-bit bytes and they are objects of class String. Double-quoted strings allow substitution and backslash notation but single-quoted strings don’t allow substitution and allow backslash notation only for \\ and \'

Example

#!/usr/bin/ruby -w

puts 'escape using "\\"';
puts 'That\'s right';

这会产生以下结果 −

This will produce the following result −

escape using "\"
That's right

您可以使用序列 #{ expr } 将任何 Ruby 表达式的值替换到字符串中。这里,expr 可以是任何 Ruby 表达式。

You can substitute the value of any Ruby expression into a string using the sequence #{ expr }. Here, expr could be any ruby expression.

#!/usr/bin/ruby -w

puts "Multiplication Value : #{24*60*60}";

这会产生以下结果 −

This will produce the following result −

Multiplication Value : 86400

Backslash Notations

以下列出了 Ruby 支持的反斜杠表示法 −

Following is the list of Backslash notations supported by Ruby −

Notation

Character represented

\n

Newline (0x0a)

\r

Carriage return (0x0d)

\f

Formfeed (0x0c)

\b

Backspace (0x08)

\a

Bell (0x07)

\e

Escape (0x1b)

\s

Space (0x20)

\nnn

Octal notation (n being 0-7)

\xnn

Hexadecimal notation (n being 0-9, a-f, or A-F)

\cx, \C-x

Control-x

\M-x

Meta-x (c

0x80)

\M-\C-x

Meta-Control-x

\x

有关 Ruby 字符串的更多详细信息,请参阅 Ruby Strings

For more detail on Ruby Strings, go through Ruby Strings.

Ruby Arrays

Ruby 数组的字面意思是由在方括号之间放置逗号分隔的对象引用序列创建的。忽略结尾逗号。

Literals of Ruby Array are created by placing a comma-separated series of object references between the square brackets. A trailing comma is 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 result −

fred
10
3.14
This is a string
last element

有关 Ruby 数组的更多详细信息,请参阅 Ruby Arrays

For more detail on Ruby Arrays, go through Ruby Arrays.

Ruby Hashes

字面 Ruby 哈希是通过将键值对列表放置在大括号内创建的,键和值之间用逗号或序列 ⇒ 隔开。忽略结尾逗号。

A literal Ruby Hash is created by placing a list of key/value pairs between braces, with either a comma or the sequence ⇒ between the key and the value. A trailing comma is 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 result −

red is 3840
green is 240
blue is 15

有关 Ruby 哈希的更多详细信息,请参阅 Ruby Hashes

For more detail on Ruby Hashes, go through Ruby Hashes.

Ruby Ranges

范围表示一个区间,这是一个具有一定值和结尾的间隔。可以使用 s..e 和 s…​e 字面值或使用 Range.new 构建范围。

A Range represents an interval which is a set of values with a start and an end. Ranges may be constructed using the s..e and s…​e literals, or with Range.new.

使用 .. 构建的范围从头到尾(含)。使用 …​ 创建的那些范围不包括结尾值。作为一个迭代器时使用范围,范围返回序列中的每个值。

Ranges constructed using .. run from the start to the end inclusively. Those created using …​ exclude the end value. When used as an iterator, ranges return each value in the sequence.

范围 (1..5) 表示它包括 1、2、3、4、5 值,范围 (1…​5) 表示它包括 1、2、3、4 值。

A range (1..5) means it includes 1, 2, 3, 4, 5 values and a range (1…​5) means it includes 1, 2, 3, 4 values.

Example

#!/usr/bin/ruby

(10..15).each do |n|
   print n, ' '
end

这会产生以下结果 −

This will produce the following result −

10 11 12 13 14 15

有关 Ruby 范围的更多详细信息,请参阅 Ruby Ranges

For more detail on Ruby Ranges, go through Ruby Ranges.