Add ruby class methods or instance methods dynamically?

Here's something re-worked to use class methods. It's kind of ugly because it's such an edge case for Ruby: class B def self. Before_method puts "before method" end def self.

Run(method) self.class. Instance_eval do define_method(method) do before_method puts "method #{method}" end end end end.

I am quite new and would love to learn, xD! – purbon Sep 12 at 19:09 People rarely create dynamic instance methods, and dynamic class methods are even rarer still. Sadly, the semantics are kind of ugly because of how infrequently it comes up.

There's nothing wrong with doing it, but most people never will, that's all. – tadman Sep 12 at 19:14 Ok! Thanks!

I have to say, I am learning, but quite happy with the language, although I sounds like a hype for me, xD! – purbon Sep 12 at 19:18 This probably isn't what you want: you've now added the method to Class, which means it is available in every class (B. Class == Class).

This is a problem especially because not every class has a 'before_method'. Try calling B. Run 'foo', defining a class A and calling A.foo.

It will fail with NameError: undefined local variable or method before_method' for A:Class` – Confusion Sep 12 at 19:40 I thought people created dynamic methods fairly frequently in Ruby; that's where a lot of the "magic" comes from. Am I confusing terminology? – Dᴀᴠᴇ Nᴇᴡᴛᴝɴ Sep 12 at 21:36.

Instance methods of an objects singleton class are singleton methods of the object itself. So if you do class B def self. Run(method) singleton_class = class Method foo (Edit: added B.

Run :foo as per Lars Haugseth's comment).

You'll want to do B. Run :foo before you can call B.foo. – Lars Haugseth Sep 12 at 20:42 You can also avoid send by using eigenclass.

Class_eval { define_method(method) { ... }} – Lars Haugseth Sep 12 at 20:55 1 Edited to use the official terminology of singleton_class, introduced in Ruby 1.9.2 – Marc-André Lafortune Sep 12 at 22:28 @Marc-André: ah, I wasn't aware there finally was a standard; we're still at 1.8.7. Now I'll have to unlearn our company standard 'eigenclass' :). – Confusion Sep 120 at 7:37.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions