Ruby大概有40多个全局变量(不同的版本不一样,ruby1.8.7有47个,ruby1.9.3有55个),这些全局变量以$开头,后接一个非字母字符的形式命名。如 $_、$+等,显的很诡异。如果不常用到,就会忘记他们的含义。不过,Ruby自带一个English库,里边引进了与这些全局变量的别名,以更友好的英文名字命名。
比如下面是English库中的部分源码:
# The exception object passed to +raise+.
alias $ERROR_INFO $!
# The stack backtrace generated by the last
# exception. See Kernel.caller for details. Thread local.
alias $ERROR_POSITION $@
# The default separator pattern used by String.split. May be
# set from the command line using the -F flag.
alias $FS $;
# The default separator pattern used by String.split. May be
# set from the command line using the -F flag.
alias $FIELD_SEPARATOR $;
# The separator string output between the parameters to methods such
# as Kernel.print and Array.join. Defaults to +nil+,
# which adds no text.
alias $OFS $,
下面列出常见的全局变量:
$! 最近一次的错误信息
$@ 错误产生的位置
$_ gets最近读的字符串
$. 解释器最近读的行数(line number)
$& 最近一次与正则表达式匹配的字符串
$~ 作为子表达式组的最近一次匹配
$n 最近匹配的第n个子表达式(和$~[n]一样)
$= 是否区别大小写的标志
$/ 输入记录分隔符
$\ 输出记录分隔符
$0 Ruby脚本的文件名
$* 命令行参数
$$ 解释器进程ID
$? 最近一次执行的子进程退出状态
另外,可以使用global_variables这个全局方法来查看所有的全局变量名。
irb(main):001:0> global_variables
=> [:$;, :$-F, :$@, :$!, :$SAFE, :$~, :$&, :$`, :$', :$+, :$=, :$KCODE, :$-K, :$,, :$/, :$-0, :$\, :$_, :$stdin, :$stdout, :$stderr, :$>, :$<, :$., :$FILENAME,:$-i, :$*, :$?, :$$, :$:, :$-I, :$LOAD_PATH, :$", :$LOADED_FEATURES, :$VERBOSE,:$-v, :$-w, :$-W, :$DEBUG, :$-d, :$0, :$PROGRAM_NAME, :$-p, :$-l, :$-a, :$binding, :$1, :$2, :$3, :$4, :$5, :$6, :$7, :$8, :$9]