Marlin Pierce
Marlin Pierce

Reputation: 10089

ruby metaprogramming super class not inheriting

When I create an anonymous class with Array as the super class, the Array methods << and []= are not getting inherited. My code below

class SubArray < Array
end

sa = SubArray.new
sa << "foo"
puts sa.inspect

sa_meta = Class.new(Array)
sa_meta << "foo"
puts sa_meta.inspect

gives the results:

["foo"]
lib/so_example1.rb:9:in `<main>': undefined method `<<' for #<Class:0x6b10b8e4> (NoMethodError)

My ruby version is:

ruby 1.9.3p194 (2012-04-20 revision 35410) [i386-darwin11.4.2]

How can I dynamically create a class, with a super-class?

Upvotes: 1

Views: 115

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

the Array methods << and []= are not getting inherited

Sure they are! Just don't forget to create an instance of the class.

sa_meta_klass = Class.new(Array)
sa_meta = sa_meta_klass.new
sa_meta << "foo"
puts sa_meta.inspect
# >> ["foo"]

Upvotes: 6

Related Questions