您的位置:首页 > 编程语言 > Ruby

Ruby学习笔记_Ruby的全局变量

2014-04-07 21:30 344 查看
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. <tt>See Kernel.caller</tt> for details. Thread local.

alias $ERROR_POSITION $@

# The default separator pattern used by <tt>String.split</tt>. May be

# set from the command line using the <tt>-F</tt> flag.

alias $FS $;

# The default separator pattern used by <tt>String.split</tt>. May be

# set from the command line using the <tt>-F</tt> flag.

alias $FIELD_SEPARATOR $;

# The separator string output between the parameters to methods such

# as <tt>Kernel.print</tt> and <tt>Array.join</tt>. Defaults to +nil+,

# which adds no text.

alias $OFS $,

下面列出常见的全局变量:

$! 最近一次的错误信息

$@ 错误产生的位置

$_ gets最近读的字符串

$. 解释器最近读的行数(line number)

$& 最近一次与正则表达式匹配的字符串

$~ 作为子表达式组的最近一次匹配

$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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: