我试图在我的一个类中将一个数组数组定义为一个常量,代码如下所示: Constant = [[1,2,3,4], [5,6,7,8]] 当我在irb中加载课程时,我得到: NoMethodError: undefined method `[]' for nil:NilClass 我尝试使用
Constant = [[1,2,3,4], [5,6,7,8]]
当我在irb中加载课程时,我得到:
NoMethodError: undefined method `[]' for nil:NilClass
我尝试使用%w并且所做的只是把每一个变成一个字符串所以我得到“[1,2,3,4]”而不是[1,2,3,4]
如何将数组数组定义为常量?
我使用ruby 1.8.7.
当我在IRB中定义常量时它很好,但是当我用它加载类时我得到一个错误.
require 'file_with_class.rb' NoMethodError: undefined method `[]' for nil:NilClass from ./trainbbcode/tags.rb:2 from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require' from (irb):1
那个文件看起来像这样:
class TBBC Tags = [[/\[b\](.*?)\[\/b\]/,'<strong>\1</strong>',@config[:strong_enabled]], ... [/\[th\](.*?)\[\/th\]/,'<th>\1</th>',@config[:table_enabled]]]你展示的代码工作得很好.您肯定没有收到该特定行的错误消息.错误是由其他地方引起的.
是的,%w创建了一个字符串数组.要创建普通数组,请使用[].
现在编辑您已显示真实代码:
@config在您使用它的范围内是nil,因此当您执行@config [:strong_enabled]时会出现异常.
请注意,在类定义的内部,但在任何方法定义之外@foo引用类对象的实例变量,而不是任何特定实例的实例变量(因为它引用了哪一个?当时甚至没有任何实例,当常量初始化).