On 5/2/05, Andreas Habel <mail / exceptionfault.de> wrote:
> Hi Mark,
> 
> I tried to implement your code and got very confused receiving the
> following error.. What`s wrong ???
> 
> ----
> 
> class Class
> 
>    def enumerate(*symb)
>      @enumerations = {}
>      symb.each_with_index do |sym, idx|
>        @enumerations[sym] = idx + 1
>      end
>    end
> 
>    def enum_val(sym)
>      @enumerations[sym]
>    end
> 
> end
> 
> class MyClass
>    enumerate :a, :b, :c
>    enumerate :x, :y, :z
> 
>    def foo( enum1, enum2 )
>      p enum_val(enum1)
>      p enum_val(enum2)
>    end
> 
> end
> 
> p Class.public_method_defined?( 'enum_val' )
> p MyClass.public_method_defined?( 'enum_val' )
> p MyClass.new.foo( :a, :y)
> 
> ===>
> 
> true
> false
> test.rb:21:in `foo': undefined method `enum_val' for
> #<MyClass:0x2874d40> (NoMethodError)
>          from test.rb:29

:/ that's embarrassing. Obviously I didn't test the code before I sent
it, and there was a major logic error, regarding scope.

----8<----

class Class
  def enumerate(*syms)
    @enumerations ||= {}
    enums = @enumerations
    syms.each_with_index do |sym, idx|
      enums[sym] = idx + 1
    end
    define_method(:enum_val) do |sym|
      enums[sym]
    end
  end
end

class MyClass
  enumerate :a, :b, :c
  enumerate :x, :y, :z
  
  def foo(enum1, enum2)
    [enum_val(enum1), enum_val(enum2)]
  end

end

p MyClass.new.foo(:a, :y)

----8<----

... prints "[1, 2]"

Sorry 'bout that. I should have caught the glaring error.

cheers,
Mark