Im trying to define an array of arrays as a Constant in one of my classes, the code looks like this:
Constant = [[1,2,3,4],
[5,6,7,8]]
When I load up the class in irb I get:
NoMethodError: undefined method `[]' for nil:NilClass
I tried using %w and all that did was turn each one into a string so i got “[1,2,3,4]” instead of [1,2,3,4]
how do I define an array of arrays as a constant?
Im using ruby 1.8.7.
When I define the constant in IRB its fine, but when I load up the class with it in i get an error.
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
That file looks like this:
class TBBC
Tags = [[/\[b\](.*?)\[\/b\]/,'<strong>\1</strong>',@config[:strong_enabled]],
...
[/\[th\](.*?)\[\/th\]/,'<th>\1</th>',@config[:table_enabled]]]
The code you showed works just fine. You’re definitely not getting that error message for that particular line. The error is caused elsewhere.
And yes,
%wcreates an array of strings. To create normal arrays use[]like you did.Edit now that you’ve shown the real code:
@configisnilin the scope where you use it, so you get an exception when you do@config[:strong_enabled].Note that inside of a class definition but outside of any method definition
@foorefers to the instance variable of the class object, not that of any particular instance (because which one would it refer to? There aren’t even any instances yet, when the constant is initialized).