Forum: Ruby How to create dinamicly method

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Be07c8d0d6867fd9a0d525f7d17600e2?d=identicon&s=25 Damjan Rems (ther)
on 2007-03-15 14:57
What I am trying to accomplist is:

  class MyClass
    def addVar(var, val)
      instance_variable_set("@#{var}", val)
      define_method("#{var}")  { || instance_variable_get("#{var}") }
    end
  end

  c = MyClass.new
  c.addVar('aa',10)  # here pops the error
  c.aa   # should return 10

But I get this error:
NoMethodError: undefined method `define_method' for #<MyClass:0x2d01cc0
@aa=10>
        from (irb):4:in `addVar'
        from (irb):8

I know this should work because it's used all over rails.

Advice me please

TheR
F0afd024e17c0c4753aa8d618ba9bb0f?d=identicon&s=25 Marcin Raczkowski (Guest)
on 2007-03-15 15:07
(Received via mailing list)
On Thursday 15 March 2007 13:57, Damjan Rems wrote:
>   c.addVar('aa',10)  # here pops the error
> Advice me please
>
> TheR
define_method won't work in instance method, you have to use class
method o
just use eval("def #{var}; here return value; end");
Be07c8d0d6867fd9a0d525f7d17600e2?d=identicon&s=25 Damjan Rems (ther)
on 2007-03-15 15:17
Marcin Raczkowski wrote:
> On Thursday 15 March 2007 13:57, Damjan Rems wrote:
>>   c.addVar('aa',10)  # here pops the error
>> Advice me please
>>
>> TheR
> define_method won't work in instance method, you have to use class
> method o
> just use eval("def #{var}; here return value; end");

Yep: Each of these two variants work:
     eval "def #{var};instance_variable_get('@#{var}');end"
     eval("def #{var}; @#{var}; end")

I was trying this too, but forgot to add @ to variable name.


Thanks

TheR
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (Guest)
on 2007-03-16 22:47
(Received via mailing list)
On Thu, Mar 15, 2007 at 10:57:54PM +0900, Damjan Rems wrote:
> What I am trying to accomplist is:
>
>   class MyClass
>     def addVar(var, val)
>       instance_variable_set("@#{var}", val)
>       define_method("#{var}")  { || instance_variable_get("#{var}") }

        self.class.class_eval {
          define_method("#{var}")  { || instance_variable_get("@#{var}")
}
        }

>     end
>   end
>
>   c = MyClass.new
>   c.addVar('aa',10)  # here pops the error
>   c.aa   # should return 10

Regards,

Brian.
This topic is locked and can not be replied to.