开发者

Behaviour of local_variables - can anybody explain?

just curious why I cann't remove declared local variable from 'local_variables' array.

Example:

x=1
myarr = local_variables.clone
p local_variables
=> [:x, :_]
p myarr
=> [:x, :_]
p local_variable开发者_如何学JAVAs.class
=> Array
p myarr.class
=> Array
myarr.delete :x
p myarr
=> [:_]
local_variables.delete :x
p local_variables
=> [:x, :_]

WTF ?

I did suspected calling local_variables.delete with parameter :x reinserts it back as it is declared anew. But if called with other previously undeclared symbol does not change it:

p local_variables
=> [:x, :_]
local_variables.delete :whatever
p local_variables
=> [:x, :_]

Can somebody explain ?

Thx.


local_variables returns an array containing the names of all currently declared local variables. You can do anything you want with that array, but this is obviously not going to affect which local variables are declared. Why would it? If you strike out a name from phone book, does that person die?


Consider the following method:

def foo
  [42, 23, 13]
end

foo #=> [42, 23, 13]
foo.delete 23
foo #=> [42, 23, 13]

Does that behaviour surprise you?

Every time you call local_variables (or foo) a new array is created. If you modify that new array that has no effect on what will happen if you call local_variables again.


AFAIK it's not possible to remove variables:

http://programming.itags.org/ruby/64695/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜