same method as class and instance methods? 
Author Message
 same method as class and instance methods?

Hi there,

I want to use a method as a class method, but as I use it frequently in
the classes' other methods, I do not want to prefix the method name with
class name in these cases. Is there a language construct to use a method
both as class and as instance methods?

Anyway, I have a workaround as defining a method like:

def methodName
  ClassName.methodName
end

Thanks:
Circum



Thu, 10 Feb 2005 02:30:38 GMT  
 same method as class and instance methods?

Quote:

> Hi there,

> I want to use a method as a class method, but as I use it frequently in
> the classes' other methods, I do not want to prefix the method name with
> class name in these cases. Is there a language construct to use a method
> both as class and as instance methods?

> Anyway, I have a workaround as defining a method like:

> def methodName
>   ClassName.methodName
> end

> Thanks:
> Circum

That is very clever.

class MyClass
  def meth
    self.type.meth
  end
  def self.meth
    puts "MyClass::meth"
  end
end

MyClass.meth      #=> MyClass::meth
MyClass.new.meth  #=> MyClass::meth

What about creating an attr_instance_method module like:

class Module
  def attr_instance_method(*class_methods)
    class_methods.each { |class_method|
      class_eval %{
        def #{class_method}
          self.type.#{class_method}
        end
      }
    }
  end
end#attr_instance_method

So, the above would be

class MyClass
  attr_instance_method :meth
  def self.meth
    puts "MyClass::meth"
  end
end

--
Jim Freeze
If only I had something clever to say for my comment...
~



Thu, 10 Feb 2005 09:23:35 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. accessing a instance method from a class method

2. Class methods vs Instance methods

3. Class method vs instance method???

4. Class method vs instance method???

5. Class Methods (as opposed to Instance Methods)

6. Object Tcl question - Class method and Instance method

7. Classes - instance/class, methods/members, inheritance and best p ractices

8. Classes - instance/class, methods/members, inheritance and be st practices

9. Singleton methods and instance methods with same name?

10. IncrTcl: calling static methods vs instance methods

11. Class vs Instance methods

12. Class vs Instance methods

 

 
Powered by phpBB® Forum Software