Ruby local_variables返回:符号? [英] Ruby local_variables returns :symbols?

查看:85
本文介绍了Ruby local_variables返回:符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览ruby内核文档,并看到了这种方法:

I was looking through the ruby Kernel doc and saw this method:

a = 2
local_variables # => [:a, :_]

为什么它返回:a而不是a? 我以为:"是为符号保留的,但是符号:a既不指向变量a也不指向变量的赋值2.

Why does it return :a and not a? I thought the ":" was reserved for symbols, but the symbol :a doesn't point to the variable a nor to it's assigned value, 2.

此外,我将如何通过该方法访问实际变量?就像在b = local_variables.first中一样(本来是2,但是是:a).

Furthermore, how would I go about accessing the actual variables through this method? As in b=local_variables.first (would be 2, but is :a).

此行为背后是否有原因,这是什么?

Is there a reason behind this behavior, what is it?

谢谢/

推荐答案

为什么它返回:a而不是a?我以为:"是为符号保留的

Why does it return :a and not a? I thought the ":" was reserved for symbols

这是预期的行为.根据文档:

It's the expected behavior. According to the docs:

返回当前局部变量的名称.

是的,这只是返回一个符号数组.

So yes, this just returns an array of symbols.

此外,我将如何通过该方法访问实际变量?

Furthermore, how would I go about accessing the actual variables through this method?

如乔纳森·卡梅尼奇(Jonathan Camenisch)所述,Ruby 2.1引入了 Binding#local_variable_get :

As noted by Jonathan Camenisch, Ruby 2.1 introduced Binding#local_variable_get:

a = 2
binding.local_variable_get(:a)
#=> 2

对于较旧的红宝石,您可以使用eval:

For older Rubies, you could use eval:

a = 2
eval(:a.to_s)
#=> 2


此行为背后是否有原因,这是什么?

Is there a reason behind this behavior, what is it?

在Ruby中,符号用作参考:

In Ruby symbols are used for references:

"foo".methods
#=> [:<=>, :==, :===, :eql?, :hash, :casecmp, ...]

Module.constants
#=> [:Object, :Module, :Class, :BasicObject, :Kernel, :NilClass, ...]

这篇关于Ruby local_variables返回:符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆