ruby - 为什么 local_variables 会返回尚未分配的局部变量?

标签 ruby

为什么 local_variables 返回尚未分配的局部变量(在调用 local_variables 之后分配)?

a = 2
@aa = 1
# a = b # this will raise an error.
puts "local: #{ local_variables }"
puts "instance: #{ instance_variables }"

b = 2
@bb = 2
puts "local: #{ local_variables }"
puts "instance: #{ instance_variables }"

结果:

local: [:a, :b]
instance: [:@aa]
local: [:a, :b]
instance: [:@aa, :@bb]

我期望的是像 instance_variables 这样的行为,它只返回当时已经分配的变量。

最佳答案

Kernel#local_variables列出当前范围内的所有局部变量,包括那些可能尚未赋值的局部变量。 MRI解析每个作用域中的局部变量并在代码本身(例如下面的 puts local_variables.inspect)运行之前声明它们,因此即使在那些之前调用 local_variables 时它们也会出现变量已定义

但请注意,defined? 仍会为调用 local_variables 时尚未分配给的变量返回 nil:

$ cat /tmp/locals
#!/usr/bin/env ruby

a = 5
puts local_variables.inspect
puts defined?(a)
puts (defined?(b) || "[undefined]")
b = 10
puts defined?(b)

def foo
  c = 15
  puts local_variables.inspect
  d = 20
end
foo

$ ruby /tmp/locals
[:a, :b]
local-variable
[undefined]
local-variable
[:c, :d]

关于ruby - 为什么 local_variables 会返回尚未分配的局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15676360/

相关文章:

ruby-on-rails - 简单的 Rails 注释添加额外的空白注释

ruby-on-rails - 将 Ruby Gems 类比为 Java JAR 是否有效?

ruby - 目前有没有办法在 faSTLane 操作中提取 faSTLane 操作的输出?

mysql - 在 Ruby on Rails 中动态连接到第二个 MySQL 数据库

ruby-on-rails - Rails 5 - Shrine 问题 : "undefined method ` cached_image_data' for nil:NilClass"

javascript - rails : JS Controller Being Called Twice for Some Reason

ruby - 如何向 ruby​​ -n -e 提供 $INPUT_RECORD_SEPARATOR?

ruby - 如何通过一组新的给定键更改散列的所有键

ruby-on-rails - 我如何在 Ruby/Rails 中获得每月的第一个星期四?

ruby-on-rails - 为什么这段 Ruby 代码无法写入日志文件?