Ruby local_variables returns :symbols?

半腔热情 提交于 2019-12-11 08:11:11

问题


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

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

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.

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?

Thanks/


回答1:


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

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

Returns the names of the current local variables.

So yes, this just returns an array of symbols.


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

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

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

For older Rubies, you could use eval:

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

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

In Ruby symbols are used for references:

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

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



回答2:


Why does it return :a and not a?

It can't return a, because a is a variable and variables aren't objects in Ruby. Methods can only take, return, and manipulate objects.




回答3:


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

Humm.here you can go:-

a = 2
b = 10
local_variables.each{|e| p eval(e.to_s)}
# >> 2
# >> 10

Why does it return :a and not a?

That answer has been given by @Stefan. But you can get here some more taste:-

13 Ways of Looking at a Ruby Symbol

Out of these the below is related to your answer:-

7. A Ruby symbol is a Ruby identifier

In Ruby, we can look up identifiers (variable, methods and constant names) while the program is running. This is typically done using symbols.

class Demo
  # The stuff we'll look up.
  DEFAULT = "Hello"
  def initialize
    @message = DEFAULT
  end
  def say() @message end

  # Use symbols to look up identifiers.
  def look_up_with_symbols
    [Demo.const_get(:DEFAULT),
     method(:say),
     instance_variable_get(:@message)]
  end
end

Demo.new.look_up_with_symbols


来源:https://stackoverflow.com/questions/18618230/ruby-local-variables-returns-symbols

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!