红宝石中全局变量的全局性如何?

Ren*_*ger 1 ruby

这是一个ruby脚本:

discarded_rows=-1

def foobar(line)

    if line.match('records discarded: *(\d+)') then
       discarded_rows=$1;
       puts('yepp, I have found: ' + discarded_rows);
    end;

end


foobar('records successful:    99    ');
foobar('records discarded:      2    ');
foobar('records unknown:        8    ');

if discarded_rows != 2 then
   puts("discarded_rows: #{discarded_rows}");
end
Run Code Online (Sandbox Code Playgroud)

这就是我认为它的作用:它声明了一个带有名称的(全局)变量discarded_rows.然后它声明一个函数foobar,检查传递的参数是否line匹配"丢弃的记录*\d".如果是,它将丢弃的记录数量分配给(我认为是全局的)变量discarded_rows.如果匹配,它还会打印"yepp ...."以确保匹配正常.

调用该函数,其中一个字符串应该匹配.

如果discarded_rows不等于2,则打印相应的值.

这是脚本的输出:

yepp, I have found: 2
discarded_rows: -1
Run Code Online (Sandbox Code Playgroud)

所以,显然,这场比赛有效,而且显然discarded_rows不是真正的全球性.这是正确的还是我忽略了什么?

Zab*_*bba 8

discarded_rows不是一个全局变量.$discarded_rows将是一个全球变量.