From: Pit Capitain Date: 2005-12-27T17:25:51+09:00 Subject: Re: can't figure out what's wrong Erik, there are some typos in your code. See below. erik blas schrieb: > I'm reading the why's ruby guide, and i've retyped a class in the guide > to use through the metaprogramming chapter. when i try to use it with > irb i get this error: > nomethoderror: undefined method '[]=] for nil:class > from path/dwemthy.rb:18:in 'life' This means that in line 18, you tried to call method "[]=" on nil. Nil doesn't have such a method, so the NoMethodError is raised. > from path/dwemthy.rb:16:in 'life' > from path/rabbit.rb:4 > > here's the code for dwemthy.rb: > class Creature > > # get a metaclass for this class > def self.metaclass; class << self; self; end; end > > # advanced metaprogramming cord for clean traits > def self.traits( *arr ) > return @traits if arr.empty? > > # 1. setup accessors for each variable > attr_accessor *arr > > # 2. add a new class method to each trait > arr.each do |a| > metaclass.instance_eval do > define_method( a ) do |val| > @triats ||= {} > @traits[a] = val This is line 18. It looks like an assignment, but it really is a method call. It calls method "[]=" on the object @traits with arguments a and val. The error message above means that @traits is nil. If you look at the previous line (line 17), you notice the typo. > end > end > end > > # 3. for each monster, the 'initialize' method should use > # the default number for each trait > class_eval do > define_method( :initialize ) do > self.class.traits.each do |k,v| > instance_varable_set("@#{k}", v) This should be "instance_variable_set". Note the missing "i". > end > end > end > end I haven't looked further. HTH. Regards, Pit