Blogged by Ujihisa. Standard methods of programming and thoughts including Clojure, Vim, LLVM, Haskell, Ruby and Mathematics written by a Japanese programmer. github/ujihisa

Tuesday, April 27, 2010

Several Ways of Defining Class/Instance Methods

This entry is for Ruby beginners.

Class Methods

Assume you have class A and want to define a class method c.

  1. class + def + self.

    1. There are so many ways...

      In Ruby 1.9:

      A.define_singleton_method :i do
      'hi'
      end

      A.singleton_class.class_eval do
      def i
      'hi'
      end
      end

      A.singleton_class.instance_eval do
      define_method :i do
      'hi'
      end
      end

      ReplyDelete
    2. Yes! I like the new feature :-D

      ReplyDelete

Followers