首页 > 学院 > 开发设计 > 正文

Ruby 中$开头的全局变量、内部变量、隐藏变量介绍

2019-10-26 19:22:35
字体:
来源:转载
供稿:网友

Ruby 中充满了一系列的隐藏变量,我们可以从这些预定义的全局变量中获取一些有意思的信息。

全局进程变量

$$ 表示当前运行的 ruby 进程。
代码如下:>> $$
=> 17170
我们可以从当前进程杀死它自己
代码如下:
>> `kill -9 #{$$}`
[1]    17170 killed     irb
$? 表示最近一个子进程的状态
代码如下:
>> `echo hello`
=> "hello/n"
>> $?
=> #<Process::Status: pid 18048 exit 0>
>> $?.success?
=> true

异常和错误

$1 表示引起异常的信息。比如在这里 raise "there's no peanut butter",它的值就是 there's no peanut butter。
代码如下:
>> begin raise "this town ain't big enough for the both of us" rescue puts $! end
this town ain't big enough for the both of us
=> nil
$@ 可以给出完整的引起错误的栈调用信息,它是一个数组。
代码如下:
>> begin raise 'no soup in kitchen' rescue $@.each { |trace| puts trace } end
(irb):13:in `irb_binding'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb/workspace.rb:80:in `eval'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb/workspace.rb:80:in `evaluate'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb/context.rb:254:in `evaluate'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb.rb:159:in `block (2 levels) in eval_input'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb.rb:273:in `signal_status'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb.rb:156:in `block in eval_input'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb/ruby-lex.rb:243:in `block (2 levels) in each_top_level_statement'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb/ruby-lex.rb:229:in `loop'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb/ruby-lex.rb:229:in `block in each_top_level_statement'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb/ruby-lex.rb:228:in `catch'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb/ruby-lex.rb:228:in `each_top_level_statement'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb.rb:155:in `eval_input'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb.rb:70:in `block in start'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb.rb:69:in `catch'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/irb.rb:69:in `start'
/home/meck/.rvm/rubies/ruby-1.9.3-p194/bin/>>'
=> ["(>>'"]


字符串和分隔符

$; 表示 String.split 里的分隔符,默认是空格。
代码如下:
>> "One Spaceship, Two Tiny Tanks, Three Misplaced Socks".split
=> ["One Spaceship", " Two Tiny Tanks", " Three Misplaced Socks"]
>> $; = ","
=> ","
>> "One Spaceship, Two Tiny Tanks, Three Misplaced Socks".split
=> ["One Spaceship", " Two Tiny Tanks", " Three Misplaced Socks"]

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表