Ruby变量
2010-07-09 星期五 小雨
ruby与大部分脚本语言不同,它有自己的命名规则(采用CoC):
1. 常量(Constants)
:首字母必须大写(一般是整个单词都是大写的)
A variable whose name begins with an uppercase letter (A-Z) is a constant. A constant can be reassigned a value after its initialization, but doing so will generate a warning. Every class is a constant.(因为/因此在ruby中,类名都是首字母大写的)
Trying to substitute the value of a constant or trying to access an uninitialized constant raises the NameError exception.
例子:FOOBAR
2. 局部变量(Local Variables)
与强类型语言(如C、C++、Java一样):
A variable whose name begins with a lowercase letter (a-z) or underscore (_) is a local variable or method invocation.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 {}.A local variable is only accessible from within the block of its initialization. For example:
i0 = 1
loop {
i1 = 2
puts defined?(i0) # true; "i0" was initialized in the ascendant block
puts defined?(i1) # true; "i1" was initialized in this block
break
}
puts defined?(i0) # true; "i0 was initialized in this block
puts defined?(i1) # false; "i1" was initialized in the loop
与脚本语言不同(如perl),不需要前面加$符号,也不需要my关键词。
3. 实例变量(Instance Variables)
A variable whose name begins with '@' is an instance variable of self. An instance variable belongs to the object itself. Uninitialized instance variables have a value of nil.
例如:@foobar
#!/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()
|
4. 类变量(Class Variables)
A class variable is shared by all instances of a class. 其实就是类静态变量
例子:@@foobar
#!/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()
|
Here @@no_of_customers is a class variable. This will produce following result:
Total number of customers: 1
Total number of customers: 2
|
5. 全局变量(Global Variables)
A variable whose name begins with '$' has a global scope; meaning it can be accessed from anywhere within the program during runtime.
例子:$foobar
6. 伪变量(Pseudo Variables)
self
Execution context of the current method.
nil
The sole-instance of the NilClass
class. Expresses nothing.
true
The sole-instance of the TrueClass
class. Expresses true.
false
The sole-instance of the FalseClass
class. Expresses false. (nil also is considered to be false, and every other value is considered to be true in Ruby.)
The value of a pseudo variable cannot be changed. Substitution to a pseudo variable causes an exception to be raised.
7. 预定义变量(Pre-defined Variables)
$! The exception information message set by the last 'raise' (last exception thrown).
$@ Array of the backtrace of the last exception thrown.
$& The string matched by the last successful pattern match in this scope.
$` The string to the left of the last successful match.
$' The string to the right of the last successful match.
$+ The last bracket matched by the last successful match.
$1 to $9 The Nth group of the last successful regexp match.
$~ The information about the last match in the current scope.
$= The flag for case insensitive, nil by default (deprecated).
$/ The input record separator, newline by default.
$\ The output record separator for the print and IO#write. Default is nil.
$, The output field separator for the print and Array#join.
$; The default separator for String#split.
$. The current input line number of the last file that was read.
$< The virtual concatenation file of the files given on command line.
$> The default output for print, printf. $stdout by default.
$_ The last input line of string by gets or readline.
$0 Contains the name of the script being executed. May be assignable.
$* Command line arguments given for the script. Same as ARGV.
$$ The process number of the Ruby running this script. Same as Process.pid.
$? The status of the last executed child process.
$: Load path for scripts and binary modules by load or require.
$" The array contains the module names loaded by require.
$LOADED_FEATURES An english friendlier alias to $"
$DEBUG The status of the -d switch. Assignable.
$FILENAME Current input file from $<. Same as $<.filename.
$KCODE Character encoding of the source code.
$LOAD_PATH An alias to $:
$stderr The current standard error output.
$stdin The current standard input.
$stdout The current standard output.
$VERBOSE The verbose flag, which is set by the -v switch.
$-0 The alias to $/
$-a True if option -a ("autosplit" mode) is set. Read-only variable.
$-d The alias to $DEBUG.
$-F The alias to $;
$-i If in-place-edit mode is set, this variable holds the extension, otherwise nil.
$-I The alias to $:
$-K The alias to $KCODE.
$-l True if option -l is set ("line-ending processing" is on). Read-only variable.
$-p True if option -p is set ("loop" mode is on). Read-only variable.
$-v The alias to $VERBOSE.
$-w True if option -w is set.
This infestation of cryptic two-character $? expressions is a thing that people will frequently complain about, dismissing Ruby as just another perl-ish line-noise language. Keep this chart handy. Note, a lot of these are useful when working with regexp code.
Note that there are some pre-defined constants at parse time, as well, namely
__FILE__ (current file)
and
__LINE__ (current line)
补充:ruby类型
Ruby Arrays:
Literals of Ruby Array are created by placing a comma-separated series of object references between 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
|
Ruby Hashes:
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
|
参考资料:
分享到:
相关推荐
### Ruby语言教程:深入解析Ruby变量类型 #### 一、引言 在编程语言中,变量扮演着极其重要的角色,它们用于存储数据并在程序运行过程中对其进行操作。Ruby 作为一种动态类型的脚本语言,提供了多种变量类型,使得...
### Ruby 变量详解 #### 一、引言 在深入了解 Ruby 变量之前,我们需要先对 Ruby 这门语言有一个基本的认知。Ruby 是一种高度动态的、面向对象的脚本语言,它由日本人松本行弘(Matsumoto Yukihiro)在 1995 年...
6、Ruby 变量 变量不能使用保留字,命名规则:小写字母 变量名只能由[a-z_0-1]组成,且只能由字母开头 使用 .class 可以获取数据的类型 variable='' # 声明变量 puts variable.class # String【Integer、Float、...
Ruby变量与数据类型 Ruby控制结构 Ruby函数与方法 Ruby面向对象编程 Ruby模块与包 Ruby错误处理 Ruby文件与I/O操作 Ruby正则表达式 Ruby网络编程 Ruby数据库交互 Ruby测试框架 RubyWeb框架Rails入门 Ruby高级特性 ...
主要介绍了Ruby 变量的的相关资料,文中详细的讲解了几种变量的概念与用法,帮助大家更好的学习,感兴趣的朋友可以了解下
本文将深入探讨Ruby语言中的类变量、全局变量、实例变量,以及多态的概念,并结合Ruby编码规范来阐述如何有效地编写代码。 一、类变量 类变量在Ruby中以`@@`前缀表示,它们是属于类或模块的共享变量,不会被类的...
Ruby有三类变量,一种常量和两种严格意义上的伪变量(pseudo-variables).变量和常量都没有类型.虽然无类型变量存在一定的缺点,但却有更多的优点并很好的符合Ruby快速简便(quick and easy)的哲学精神. 在大多数语言里...
请说明Ruby变量声明和赋值的语法。 在Ruby中,变量的声明非常简单,不需要显式指定类型。变量名区分大小写,并且以特定字符开头来表示其作用域: - **局部变量**:以小写字母或下划线开头。 - **实例变量**:以`@`...
变量分配 目标 分配局部变量。 指示 您将分配一个名为greeting的局部变量,该变量等于"Hello World" 。 您首先应该通过运行learn来确保测试套件正确运行。 在首次运行测试套件时,您应该看到: Failures: 1) ./...
ruby> $foo nil ruby> $foo = 5 5 ruby> $foo 5 应谨慎使用全局变量.由于在任何地方都可以被写因此他们相当危险.滥用全局变量会导致很难隔离臭虫;同时也视为程序的设计未经严格考虑.当你发现必须要使用全局...
变量分配 目标 分配局部变量。 指示 您将分配一个名为greeting的局部变量,该变量等于"Hello World" 。 您首先应该通过运行learn test来确保测试套件正常运行。 在首次运行测试套件时,您应该看到: Failures: 1...
变量分配 目标 分配局部变量。 指示 您将分配一个名为greeting的局部变量,该变量等于"Hello World" 。 您首先应该通过运行learn来确保测试套件正确运行。 在第一次运行测试套件时,您应该看到: Failures: 1) ....
变量分配 目标 分配局部变量。 指示 您将分配一个名为greeting的局部变量,该变量等于"Hello World" 。 您首先应该通过运行learn来确保测试套件正确运行。 在首次运行测试套件时,您应该看到: Failures: 1) ./...
变量分配 目标 分配局部变量。 指示 您将分配一个名为greeting的局部变量,该变量等于"Hello World" 。 您首先应通过运行learn test来确保测试套件正常运行。 在第一次运行测试套件时,您应该看到: Failures: 1...
Ruby中的变量有几种形式,分别是局部变量、实例变量、类变量、全局变量,对于初学者来说,常常容易搞混,尤其像本人这种做java的,理解起来还是头痛,经过仔细辨别学习,将这几种变量的差异及使用场景总结如下: ...
ruby> $foo nil ruby> @foo nil ruby> foo ERR: (eval):1: undefined local variable or method `foo’ for main(Object) 对局部变量的第一次赋值做的很像一次声明.如果你指向一个未初始化的局部变量,...
### Ruby中类变量和实例变量的比较 在Ruby编程语言中,类变量和实例变量都是用来存储数据的重要机制。它们虽然都是变量,但在用途、作用范围、生命周期等方面有着明显的区别。接下来,我们将详细介绍这两者之间的四...
### Ruby中变量引用时的一些注意点 #### 一、引言 在Ruby语言中,变量引用的处理方式具有一定的灵活性和特殊性。本篇文章将详细探讨Ruby中的变量引用及其注意事项,帮助开发者更好地理解和掌握Ruby中变量引用的工作...