Ruby学习笔记_Ruby的全局变量

来源:互联网 发布:非负矩阵分解算法综述 编辑:程序博客网 时间:2024/05/20 12:50

Ruby大概有40多个全局变量(不同的版本不一样,ruby1.8.7有47个,ruby1.9.3有55个),这些全局变量以$开头,后接一个非字母字符的形式命名。如 $_、$+等,显的很诡异。如果不常用到,就会忘记他们的含义。不过,Ruby自带一个English库,里边引进了与这些全局变量的别名,以更友好的英文名字命名。


比如下面是English库中的部分源码:


  1. # The exception object passed to +raise+.

  2. alias $ERROR_INFO $!


  3. # The stack backtrace generated by the last

  4. # exception. <tt>See Kernel.caller</tt> for details. Thread local.

  5. alias $ERROR_POSITION $@


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

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

  8. alias $FS $;


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

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

  11. alias $FIELD_SEPARATOR $;


  12. # The separator string output between the parameters to methods such

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

  14. # which adds no text.

  15. 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]



0 0