Ruby的動態類。如何修復“警告:來自頂層的類變量訪問”

[英]Ruby Dynamic Classes. How to fix “warning: class variable access from toplevel”


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:

我正在編寫一個程序,根據從文件中讀取的配置動態地定義ruby類。我知道我可以上課。新。下面是一個示例程序:

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):

運行時,我得到如下輸出(使用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

我試過替換tjhat的台詞

@@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!

提前謝謝!

3 个解决方案

#1


7  

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

為了刪除這個警告,您應該使用class_variable_set方法:

x = [1,2,3]

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

  def foo
    puts @@mylist
  end
end

#2


15  

This isn't doing what you think it's doing. Since you're not creating a class with the class keyword, your class variable is being set on Object, not Test. The implications of this are pretty huge, which is why Ruby is warning you. Class variables are shared between ancestors, and objects usually inherit from Object.

這並不是你認為的那樣。因為沒有使用class關鍵字創建類,所以類變量是在對象上設置的,而不是在測試上。它的影響是非常巨大的,這就是Ruby警告您的原因。類變量在祖先之間共享,對象通常從對象繼承。

#3


2  

Rather than defining your "mylist" class variable on the class when declaring the class, you can declare class level variables on it later on as below. Two different methods are shown. The former only works in 1.9, the latter works in both versions, but is less idiomatic.

在聲明類時,與其在類上定義“mylist”類變量,不如稍后在類上聲明類級變量,如下所示。展示了兩種不同的方法。前者僅在1.9中有效,后者在兩個版本中都有效,但不太地道。

x = [1,2,3]

Test = Class.new do
  def foo
    puts @@mylist
  end
end

# ruby 1.9.2
Test.class_variable_set(:@@mylist, x)   

# ruby 1.8.7
Test.class_eval {
  @@mylist = x
}

Test.new.foo

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/11/04/72fe9508542aee97cfd85806a7081135.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com