How can we create instance method and class methods at runtime in ruby?

How can we create instance method and class methods at runtime in ruby?

class Foo
def test
p “hi”
end
end
foo = Foo.new
foo.test # => “hi”
class Foo
def test
p “hiyy”
end
end
foo.test

>> “hi”

>> “hiyy”

How Can I re-define the test method at runtime? I tried
define_method,but it didn’t work for this.

On Jul 22, 2013, at 11:43 PM, Love U Ruby [email protected] wrote:

def test

Posted via http://www.ruby-forum.com/.

Don’t know what you’re doing, but this works:

$ irb
2.0.0p247 :001 > class Foo; def test; p “hi”; end;end
=> nil
2.0.0p247 :002 > foo = Foo.new
=> #Foo:0x007fdef1882f20
2.0.0p247 :003 > foo.test
“hi”
=> “hi”
2.0.0p247 :004 > class Foo; def test; p “bye”; end;end
=> nil
2.0.0p247 :005 > foo.test
“bye”
=> “bye”
2.0.0p247 :006 > class Foo; def self.test; p “bazinga!”; end;end
=> nil
2.0.0p247 :007 > Foo.test
“bazinga!”
=> “bazinga!”
2.0.0p247 :008 > foo.test
“bye”
=> “bye”

Sorry for creating the confusions:-

Here I tried once more to explain what I was looking for:

class Foo
def test
p “hi”
end
end
foo = Foo.new
foo.test # => “hi”
Foo.define_method(:test){p “hello”}

private method `define_method’ called for Foo:Class (NoMethodError)

Any method is there to re-define the method test without re-opening
the class in runtime?

Thanks

On Tuesday 23 July 2013 Love U Ruby wrote

foo.test # => “hi”
Foo.define_method(:test){p “hello”}

private method `define_method’ called for Foo:Class (NoMethodError)

Any method is there to re-define the method test without re-opening
the class in runtime?

Thanks


Posted via http://www.ruby-forum.com/.

You can use class_eval:

Foo.class_eval do
define_method(:test){p ‘hello’}
end

or you can use send:

Foo.send :define_method, :test, &proc{p ‘hello’}

I hope this helps

Stefano

Stefano C. wrote in post #1116318:

On Tuesday 23 July 2013 Love U Ruby wrote

Foo.class_eval do
define_method(:test){p ‘hello’}
end

or you can use send:

Foo.send :define_method, :test, &proc{p ‘hello’}

I hope this helps

Stefano

Thanks @Stefano - this is what I was looking for… :slight_smile:

On Jul 23, 2013, at 6:18 AM, Love U Ruby [email protected] wrote:

I hope this helps

Stefano

Thanks @Stefano - this is what I was looking for… :slight_smile:


Posted via http://www.ruby-forum.com/.

Be circumspect in doing this with define_method. It’s a lot slower when
you call the method: