Skip to content

Instantly share code, notes, and snippets.

@plusor
Created July 29, 2013 14:24
Show Gist options
  • Save plusor/6104647 to your computer and use it in GitHub Desktop.
Save plusor/6104647 to your computer and use it in GitHub Desktop.
Ruby 全局变量/常量

异常信息(Exception Information)

                                     #传递给raise的异常对象.
$!                Exception          #The exception object passed to raise. [thread]
                                     #最后一个异常产生时的调用栈. 详见 Kernel#caller.
$@                Array              #The stack backtrace generated by the last exception. See Kernel#caller. [thread] 

模式匹配变量(Pattern Matching Variables)

这些变量(除了$=)在模式匹配失败后被置为nil.(These variables (except $=) are set to nil after an unsuccessful pattern match.)

                                     #匹配的字符串(匹配成功之后). 此变量拒不相当于当前作用域.
$&                String             #The string matched (following a successful pattern match). This variable is local to the current scope. [r/o, thread]
                                     #成功模式匹配产生的最高序号的组的内容.这样,在"cat" =~ /(c|a)(t|z)/中,$+ 为 "t".这个变量局部于当前作用域.
$+                String             #The contents of the highest-numbered group matched following a successful pattern match. Thus, in "cat" =~/(c|a)(t|z)/, $+ will be set to “t.” This variable is local to the current scope. [r/o, thread]
                                     #匹配字符串之前的串,此变量局部于当前作用域.
$`                String             #The string preceding the match in a successful pattern match. This variable is local to the current scope. [r/o, thread]
                                     #匹配字符串之前的串,此变量局部于当前作用域.
$'                String             #The string following the match in a successful pattern match. This variable is local to the current scope. [r/o, thread]
                                     #模式匹配中连续匹配的组的内容. 在 "cat" =~ /(c|a)(t|z)/匹配后,$1为 "a",$2为"t".这些变量局部于当前作用域.
$1. . . $n        String             #The contents of successive groups matched in a successful pattern match. In "cat" =~/(c|a)(t|z)/, $1 will be set to “a” and $2 to “t.” This variable is local to the current scope. [r/o, thread]
                                     #一个封装成功匹配结果的对象.变量$&,$`,$'和$1到$9都是从$~中派生的. 对$~的赋值会改变这些派生的变量的值.此变量局部于当前作用域.
$~                MatchData          #An object that encapsulates the results of a successful pattern match. The variables $&, $`, $', and $1 to $9 are all derived from $~. Assigning to $~ changes the values of these derived variables. This variable is local to the current scope. [thread] 

"The variable $=, which previously controlled case-insensitive matches, has been removed"

输入/书橱变量(Input/Output Variables)

                                     #输入记录分隔符(默认为换行符).像Kernel#gets这样的例程用该值来区分记录边界.如果设置为nil,gets将读入整个文件.
$/                String             #The input record separator (newline by default). This is the value that routines such as Kernel#gets use to determine record boundaries. If set to nil, gets will read the entire file.
                                     #$/的同义词
$-0               String             #Synonym for $/.
                                     #附加到方法调用的(例如Kernel#print和IO#write)的输出结果的字符串.默认为nil.
$\                String             #The string appended to the output of every call to methods such as Kernel#print and IO#write. The default value is nil.
                                     #像Kernel#print,Array#join这样的方法的参数输出时的分隔字符串.默认为nil,不添加任何文本.
$,                String             #The separator string output between the parameters to methods such as Kernel#print and Array#join. Defaults to nil, which adds no text.
                                     #从当前输入文件中读入的最后一行的行号.
$.                Fixnum             #The number of the last line read from the current input file. 
                                     #String#split使用的默认分隔模式.也可以在命令行用-F选项设置.
$;                String             #The default separator pattern used by String#split. May be set from the command line using the -F flag.
                                     #一个可以访问作为命令行参数给出或者$stdin(当没有参数的时候)给出的所有文件的内容对象.$<支持的方法和File对象类似:binmode, close, closed?,each, each_byte, each_line, eof, eof?, file, filename, fileno, getc, gets, lineno,lineno=, path, pos, pos=, read, readchar, readline, readlines, rewind, seek, skip,tell, to_a, to_i, to_io, to_s一集Enumberable中的方法.file方法返回表示当前正在读的文件的File对象.返回的对象可能会改变,因为$<会一次读取命令行上给出的文件
$<                Object             #An object that provides access to the concatenation of the contents of all the files given as command-line arguments or $stdin (in the case where there are no arguments).$< supports methods similar to a File object: binmode, close, closed?,each, each_byte, each_line, eof, eof?, file, filename, fileno, getc, gets, lineno,lineno=, path, pos, pos=, read, readchar, readline, readlines, rewind, seek, skip,tell, to_a, to_i, to_io, to_s, along with the methods in Enumerable. The method file returns a File object for the file currently being read. This may change as $< reads through the files on the command line. [r/o]
                                     #Knernel#print和Kernel#printf的输出目标.默认值为$stdout.
$>                IO The             #destination of output for Kernel#print and Kernel#printf. The default value is $stdout.
                                     #Kernel#ggets或者Kernel#readline读入的最后一行.在Kernel模块中很多字符串相关的函数默认情况下都对$_操作.此变量局部于当前作用域.
$_                String             #The last line read by Kernel#gets or Kernel#readline. Many string-related functions in the Kernel module operate on $_ by default. The variable is local to the current scope. [thread]
                                     #和$;同义.
$-F               String             #Synonym for $;.
                                     #当前标准错误输出.
$stderr           IO The             #current standard error output.
                                     #当前标准输入.
$stdin            IO The             #current standard input.
                                     #当前标准输出. 对$stdout赋值的用法已经过时,使用$stdout.reopen替代.
$stdout           IO The             #current standard output. Assignment to $stdout is not permitted: use $stdout. reopen instead.

"The variables $defout and $deferr have 1.9 been removed from Ruby 1.9."

执行环境变量(Execution Environment Variables)

                                     #被执行的Ruby程序的名字.通常是程序的文件名.在某些操作系统中,对此变量赋值将会改变ps(1)命令报告的进程名字.
$0                String             #The name of the top-level Ruby program being executed. Typically this will be the program’s filename. On some operating systems, assigning to this variable will change the name of the process reported (for example) by the ps(1) command.
                                     #一个包含调用程序时给出的命令行选项的字符串数组.被Ruby解释器使用的选项已经被删除.
$*                Array              #An array of strings containing the command-line options from the invocation of the program. Options used by the Ruby interpreter will have been removed. [r/o]
                                     #一个包含require装载的文件名或者模块名的数组.
$"                Array              #An array containing the filenames of modules loaded by require. [r/o]
                                     #被执行的程序的进程号.
$$                Fixnum             #The process number of the program being executed. [r/o]
                                     #最后一个终止的子进程的退出状态.
$?                Process::Status    #The exit status of the last child process to terminate. [r/o, thread]
                                     #一个字符串数组,load和require方法将在每个字符串指定的目录中搜索Ruby脚本和二进制扩展.初始值为-I 命令行选项传入的参数,后跟安装时定义的标准库的路径,当前路径(".").在程序中可以重新设置此变量的值以调整默认搜索路径:通常,程序使用$: << dir 已将dir添加到路径中.
$:                Array              #An array of strings, where each string specifies a directory to be searched for Ruby scripts and binary extensions used by the load and require methods. The initial value is the value of the arguments passed via the -I command-line option, followed by an installation-defined standard library location, followed by the current directory (“.”). This variable may be set from within a program to alter the default search path; typically, programs use $: << dir to append dir to the path. [r/o]
                                     #如果命令行中给出-a选项,则为真.
$-a               Object             #True if the -a option is specified on the command line. [r/o]

_ _callee_ _      Symbol             #The 1.9 name of the lexically enclosing method.
                                     #$DEBUG的同义词.
$-d               Object             #Synonym for $DEBUG.
                                     #如果命令行中给出了-d选项,则为真.
$DEBUG            Object             #Set to true if the -d command-line option is specified.

_ _ENCODING_ _    String             #The encoding of the current source file. 1.9 [r/o]
                                     #当前源文件的名字.
_ _FILE_ _        String             #The name of the current source file. [r/o]
                                     #如果使用了-a命令行选项,则此数组表示分隔的输入行.
$F                Array              #The array that receives the split input line if the -a command-line option is used.
                                     #当前输入文件的名字.等价于 $<.filename.
$FILENAME         String             #The name of the current input file. Equivalent to $<.filename. [r/o]
                                     #如果启动了 in-place 编辑模式(可能使用了-i命令行选项),则$-i保存了用来保存备份文件的扩展.如果设置一个值给$-i,则将启用in-place编辑模式.
$-i               String             #If in-place edit mode is enabled (perhaps using the -i command-line option), $-i holds the extension used when creating the backup file. If you set a value into $-i, enables in-place edit mode.
                                     #与$: 同义.
$-I               Array              #Synonym for $:. [r/o]
                                     #如果命令行中给出了 -l 选项(改选项启用 line-end 处),则为真.
$-l               Object             #Set to true if the -l option (which enables line-end processing) is present on the command line. [r/o]
                                     #源代码文件中当前行的行号.
_ _LINE_ _        String             #The current line number in the source file. [r/o]
                                     #与 $: 同义.
$LOAD_PATH        Array              #A synonym for $:. [r/o]
                                     #与 $. 同义.
$LOADED_FEATURES  Array              #Synonym for $". [r/o]

_ _method_ _      Symbol             #The 1.9 name of the lexically enclosing method.
                                     # $0的别名.
$PROGRAM_NAME     String             #Alias for $0.
                                     #如果命令行中有-p选项(改选项将程序置于一个隐含的while gets..end 循环中),则为真.
$-p               Object             #Set to true if the -p option (which puts an implicit while gets . . . end loop around your program) is present on the command line. [r/o]
                                     #当前的安全级别. 不能用赋值语句来减小改变量的值.
$SAFE             Fixnum             #The current safe level. This variable’s value may never be reduced by assignment. [thread]
                                     #如果命令行中给出了-v,--version,-w或者-w选项,则为真.如果没有这些选项,或者有-wl,则为假.如果有-WO选项则为nil.将此选项设置为真将使得解释器和一些库例程输出更多额外信息. 设置为nil 将禁止所有警告(包括Kernel.warn的输出).
$VERBOSE          Object             #Set to true if the -v, --version, -W, or -w option is specified on the command line. Set to false if no option, or -W1 is given. Set to nil if -W0 was specified. Setting this option to true causes the interpreter and some library routines to report additional information. Setting to nil suppresses all warnings (including the output of Kernel.warn).
                                     #与$VERBOSE同义.
$-v               Object             #Synonym for $VERBOSE.
                                     #与$VERBOSE同义.
$-w               Object             #Synonym for $VERBOSE.
$-W               Object             #Return the value set by the -W command-line option.

标准对象(Standard Objects)

                                     #与$<同义.
ARGF              Object             #A synonym for $<.
                                     #与$*同义.
ARGV              Array              #A synonym for $*.
                                     #一个类似于 hash 的包含程序环境变量的对象. 类 Object.ENV 的实例实现了Hash的所有方法.改对象可以用来查询和设置环境变量的值,例如ENV["PATH"]和ENV["term"]="ansi"
ENV               Object             #A hash-like object containing the program’s environment variables. An instance of class Object, ENV implements the full set of Hash methods. Used to query and set the value of an environment variable, as in ENV["PATH"] and ENV["term"]="ansi".
                                     #类 FalseClass 的 Singleton 实例.
false             FalseClass         #Singleton instance of class FalseClass. [r/o]
                                     #类 NilClass 的 Singleton 实例. 表示未初始化的实例变量和全局变量的值.
nil               NilClass           #The singleton instance of class NilClass. The value of uninitialized instance and global variables. [r/o]
                                     #当前方法的接受者(对象).
self              Object             #The receiver (object) of the current method. [r/o]
                                     #TrucClass类的singleton实例
true              TrueClass          #Singleton instance of class TrueClass. [r/o]

全局常量(Global Constants)

The following constants are defined by the Ruby interpreter.

                                     #如果主程序文建含有__END__指令,那么常量DATA将会被初始化为源代码中__END__之后的行.
DATA              IO                 #If the main program file contains the directive _ _END_ _, then the constant DATA will be initialized so that reading from it will return lines following _ _END_ _ from the source file.
                                     #和 false 同义.
FALSE             FalseClass         #Constant containing reference to false.
                                     #和 nil 同义.
NIL               NilClass           #Constant containing reference to nil.
                                     #解释器的版权
RUBY_COPYRIGHT    String             #The interpreter copyright.
RUBY_DESCRIPTION  String             #Version number 1.9 and architecture of the interpreter.
RUBY_ENGINE       String             #The name of the Ruby interpreter. 1.9 Returns ruby for Matz’s version. Other interpreters include macruby, ironruby, jruby, and rubinius.
RUBY_PATCHLEVEL   String             #The patch level 1.9 of the interpreter.
                                     #运行程序的平台标识符.这个字符串和GNU configure 工具用的平台标识符有相同的形式(并不与之完全一致).
RUBY_PLATFORM     String             #The identifier of the platform running this program. 1.9 This string is in the same form as the platform identifier used by the GNU configure utility (which is not a coincidence).
                                     #版本发布的日期.
RUBY_RELEASE_DATE String             #The date of this release.
                                     #解释器的修订.
RUBY_REVISION     String             #The revision of the interpreter.
                                     #解释器的版本号.
RUBY_VERSION      String             #The version number of the interpreter.
                                     #程序实际的标准错误流.初始值为$stderr.
STDERR            IO                 #The actual standard error stream for the program. The initial value of $stderr.
                                     #程序时机的标准输入流.初始值为$stdout.
STDIN             IO                 #The actual standard input stream for the program. The initial value of $stdin.
                                     #程序实际的标准输出流.初始值为$stdout
STDOUT            IO                 #The actual standard output stream for the program. The initial value of $stdout.
                                     #如果常量SCRIPT_LINES__被定义,并引用一个Hash,那么Ruby会保存它解析的每个文件的内容为Hash的一项,键是文件的名字而值是一个字符串数组. 参见 Kernel
SCRIPT_LINES__    Hash               #If a constant SCRIPT_LINES__ is defined and references a Hash, Ruby will store an entry containing the contents of each file it parses, with the file’s name as the key and an array of strings as the value. See Kernel.
TOPLEVEL_BINDING  Binding            #A Binding object representing the binding at Ruby’s top level—the level where programs are initially executed.
                                     #和 true 同义.
TRUE              TrueClass          #A reference to the object true.

"The constant _ FILE _ and the variable $0 are often used together to run code only if it appears in the file run directly by the user. For example, library writers often use this to include tests in their libraries that will be run if the library source is run directly, but not if the source is required into another program."

# library code
# ...
if __FILE__ == $0
# tests...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment