Ruby动态类。如何修复“warning:从变量访问到类别” [英] Ruby Dynamic Classes. How to fix "warning: class variable access from toplevel"

查看:177
本文介绍了Ruby动态类。如何修复“warning:从变量访问到类别”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序,根据从文件读取的配置动态定义ruby类。我知道我可以使用Class.new来做到这一点。这是一个示例程序:

  x = [1,2,3] 

Test = Class。 new do
@@ mylist = x

def foo
puts @@ mylist
end
end

Test.new .foo

当我运行这个我得到以下输出(使用ruby 1.9.3p0运行):

 c:/utils/test.rb:4:warning:从toplevel获取类变量访问
c:/utils/test.rb:7:warning :从toplevel的类变量访问
1
2
3

有谁知道是什么原因导致这些警告,摆脱他们?



我已经尝试替换行tjhat

  @@ mylist = x  

与此

  class_variable_set(:@@ mylist,x) 

但是当我这样做这个错误代替:

 c:/utils/test.rb:7:warning:从toplevel 
c:/ utils / test的类变量访问。 rb:7:在`foo'中:未初始化的类Object(NameError)中的变量@@ mylist来自c:/utils/test.rb的
:11:在`'

提前感谢!

解决方案

只需删除此警告,您应该使用 class_variable_set

  x = [1,2,3] 

测试= Class.new do
class_variable_set(:@@ mylist,x)

def foo
puts @@ mylist
end
end
/ pre>

I'm trying to write a program that dynamically defines ruby classes based on configuration read from a file. I know I can use Class.new to do this. Here's an example program:

x = [1,2,3]

Test = Class.new do
  @@mylist = x

  def foo
    puts @@mylist
  end
end

Test.new.foo

When I run this I get the following output (running with ruby 1.9.3p0):

c:/utils/test.rb:4: warning: class variable access from toplevel
c:/utils/test.rb:7: warning: class variable access from toplevel
1
2
3

Does anyone know what causes these warnings and how I can get rid of them?

I've tried replacing the line tjhat does

@@mylist = x

with this

class_variable_set(:@@mylist, x)

But when I do that I get this error instead:

c:/utils/test.rb:7: warning: class variable access from toplevel
c:/utils/test.rb:7:in `foo': uninitialized class variable @@mylist in Object (NameError)
        from c:/utils/test.rb:11:in `'

Thanks in advance!

解决方案

Just to remove this warning, you should use class_variable_set method:

x = [1,2,3]

Test = Class.new do
  class_variable_set(:@@mylist, x)

  def foo
    puts @@mylist
  end
end

这篇关于Ruby动态类。如何修复“warning:从变量访问到类别”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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