Ruby - 变量、常量和字面量
变量是内存位置,用于存储程序中使用的任何数据。
Ruby 支持五种类型的变量。你在上一章中已经了解过这些变量的简要描述。本章将详细解释这五种类型的变量。
Ruby 全局变量
全局变量以 $ 开头。未初始化的全局变量值为 nil,并且在使用 -w 选项时会产生警告。
对全局变量的赋值会改变全局状态。不推荐使用全局变量,它们会使程序变得晦涩难懂。
以下是一个展示全局变量使用的示例。
$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 是一个全局变量。这将产生以下结果 −
注意 − 在 Ruby 中,你可以通过在变量或常量前放置哈希 (#) 字符来访问其值。
Global variable in Class1 is 10 Global variable in Class2 is 10
Ruby 实例变量
实例变量以 @ 开头。未初始化的实例变量值为 nil,并且在使用 -w 选项时会产生警告。
以下是一个展示实例变量使用的示例。
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 是实例变量。这将产生以下结果 −
Customer id 1 Customer name John Customer address Wisdom Apartments, Ludhiya Customer id 2 Customer name Poul Customer address New Empire road, Khandala
Ruby 类变量
类变量以 @@ 开头,必须在使用方法定义之前初始化。
引用未初始化的类变量会产生错误。类变量在定义它们的类或模块的子类中共享。
覆盖类变量在使用 -w 选项时会产生警告。
以下是一个展示类变量使用的示例 −
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 是一个类变量。这将产生以下结果 −
Total number of customers: 1 Total number of customers: 2
Ruby 局部变量
局部变量以小写字母或 _ 开头。局部变量的作用域从 class、module、def 或 do 到对应的 end,或者从块的开括号到闭括号 {}。
当引用未初始化的局部变量时,它会被解释为对一个无参数方法的调用。
对未初始化局部变量的赋值也相当于变量声明。这些变量的存在直到当前作用域结束为止。局部变量的生命周期在 Ruby 解析程序时确定。
在上面的例子中,局部变量是 id、name 和 addr。
Ruby 常量
常量以大写字母开头。在 class 或 module 内定义的常量可以在该 class 或 module 内访问,而在 class 或 module 外定义的常量可以全局访问。
常量不能在方法内定义。引用未初始化的常量会产生错误。对已初始化的常量进行赋值会产生警告。
class Example
VAR1 = 100
VAR2 = 200
def show
puts "Value of first Constant is #{VAR1}"
puts "Value of second Constant is #{VAR2}"
end
end
# 创建对象
object = Example.new()
object.show
这里 VAR1 和 VAR2 是常量。这将产生以下结果 −
Value of first Constant is 100 Value of second Constant is 200
Ruby 伪变量
它们是特殊变量,看起来像局部变量但行为像常量。你不能给这些变量赋值。
self − 当前方法的接收者对象。
true − 表示 true 的值。
false − 表示 false 的值。
nil − 表示未定义的值。
__FILE__ − 当前源文件的名称。
__LINE__ − 源文件中当前行号。
Ruby 基本字面量
Ruby 用于字面量的规则简单直观。本节解释所有基本的 Ruby 字面量。
整数
Ruby 支持整数。整数的范围可以是从 -230 到 230-1,或者 -262 到 262-1。在这个范围内的整数是 class Fixnum 的对象,超出这个范围的整数存储在 class Bignum 的对象中。
你可以使用可选的前导符号、可选的进制指示符(0 表示八进制,0x 表示十六进制,或 0b 表示二进制),后面跟着适当进制中的数字字符串来书写整数。在数字字符串中,下划线字符会被忽略。
你也可以通过在 ASCII 字符或转义序列前加问号来获取对应的整数值。
示例
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
注意 − Class 和 Objects 在本教程的单独章节中解释。
浮点数
Ruby 支持浮点数。它们也是数字,但带有小数点。浮点数是 class Float 的对象,可以是以下任何一种 −
示例
123.4 # floating point value 1.0e6 # scientific notation 4E20 # dot not required 4e+20 # sign before exponential
字符串字面量
Ruby 字符串只是 8 位字节的序列,它们是
示例
#!/usr/bin/ruby -w puts 'escape using "\\"'; puts 'That\'s right';
这将产生以下结果 −
escape using "\" That's right
您可以使用序列 #{ expr } 将任何 Ruby 表达式的值替换到字符串中。这里,expr 可以是任何 Ruby 表达式。
#!/usr/bin/ruby -w
puts "Multiplication Value : #{24*60*60}";
这将产生以下结果 −
Multiplication Value : 86400
反斜杠表示法
以下是 Ruby 支持的反斜杠表示法列表 −
| 表示法 | 表示的字符 |
|---|---|
| \n | 换行 (0x0a) |
| \r | 回车 (0x0d) |
| \f | 换页 (0x0c) |
| \b | 退格 (0x08) |
| \a | 铃声 (0x07) |
| \e | 转义 (0x1b) |
| \s | 空格 (0x20) |
| \nnn | 八进制表示法 (n 为 0-7) |
| \xnn | 十六进制表示法 (n 为 0-9, a-f 或 A-F) |
| \cx, \C-x | Control-x |
| \M-x | Meta-x (c | 0x80) |
| \M-\C-x | Meta-Control-x |
| \x | 字符 x |
有关 Ruby 字符串的更多详细信息,请参阅 Ruby Strings。
Ruby 数组
Ruby 数组的字面量是通过在方括号之间放置用逗号分隔的对象引用序列来创建的。尾随逗号会被忽略。
示例
ary = [ "fred", 10, 3.14, "This is a string", "last element", ] ary.each do |i| puts i end
这将产生以下结果 −
fred 10 3.14 This is a string last element
有关 Ruby 数组的更多详细信息,请参阅 Ruby Arrays。
Ruby Hash
Ruby Hash 的字面量是通过在大括号之间放置键/值对列表来创建的,键和值之间用逗号或序列 => 分隔。尾随逗号会被忽略。
示例
hsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }
hsh.each do |key, value|
print key, " is ", value, "\n"
end
这将产生以下结果 −
red is 3840 green is 240 blue is 15
有关 Ruby Hash 的更多详细信息,请参阅 Ruby Hashes。
Ruby 范围
Range 表示一个区间,它是一组具有起始和结束值的值的集合。范围可以使用 s..e 和 s...e 字面量或 Range.new 构造。
使用 .. 构造的范围从起始到结束包含所有值。使用 ... 构造的范围排除结束值。当用作迭代器时,范围会返回序列中的每个值。
范围 (1..5) 表示包含 1、2、3、4、5 值,范围 (1...5) 表示包含 1、2、3、4 值。
示例
(10..15).each do |n| print n, ' ' end
这将产生以下结果 −
10 11 12 13 14 15
有关 Ruby 范围的更多详细信息,请参阅 Ruby Ranges。