tags:

views:

60

answers:

3

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]]]
+1  A: 

It's a bit strange to use a TitleCase name for a constant. But regardless, it works for me:

$ ruby --version
ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-darwin9.7.0]
$ irb --version
irb 0.9.5(05/04/13)
$ irb
irb(main):001:0> Constant = [[1,2,3,4],[5,6,7,8]]
=> [[1, 2, 3, 4], [5, 6, 7, 8]]

I also tested it in Ruby 1.9.1. Could you be more specific?

Michael Melanson
+5  A: 

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, %w creates an array of strings. To create normal arrays use [] like you did.

Edit now that you've shown the real code:

@config is nil in 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 @foo refers 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).

sepp2k
A: 

This works in irb for me......what version of ruby are you using?

ennuikiller