def and undef a method

Posted by root Sat, 26 Jul 2008 04:50:00 GMT

  def my_method; end # define a method
  undef my_method    # remove a method
The core manual

Posted in  | Tags  | no comments

Simple class's variable accessor

Posted by root Sun, 20 Jul 2008 04:13:00 GMT

class Class
  def attr(arg)
    arg = arg.to_s
    if self.class_variables.include?(arg)
      class_eval %(def self.#{arg.sub(/^\@\@/, '')}; #{arg}; end)
    else
      raise ArgumentError, "No such class attribute", caller
    end
  end
end

class Test
  @@class_var = "class variable value"

  attr :@@class_var
end

puts Test.class_var => "class variable value"

Posted in  | Tags  | no comments

Getting an indication of the number of arguments accepted by a method

Posted by root Mon, 16 Jun 2008 08:57:00 GMT

class Object
  def arguments?(*methods)
    methods.each do |method|
      begin
        rval = self.method(method).arity
        if rval > 0
          puts "'#{method}' takes fixed (#{rval}) number of argument"
        elsif rval < 0
          puts "'#{method}' takes variable number of arguments"
        elsif rval == 0
          puts "'#{method}' takes no arguments"
        end
      rescue
       puts $!
      end
    end
  end
end

String.new.arguments?(:size, :to_i, :scan, :flatten)

www.ruby-doc.org arity

Posted in  | Tags  | no comments

Convert an array to a hash

Posted by root Sun, 04 May 2008 21:56:00 GMT

class Array
  def to_h
    arr = self.dup
    if arr.size % 2 == 0
        Hash[*arr]
    else
        Hash[*arr << nil]
    end
  end
end

Posted in  | Tags  | no comments

Dynamically Define Methods

Posted by root Fri, 11 Jan 2008 07:21:00 GMT

Perl
package MyClass;
package main;

*MyClass::from_my_class = sub { 
   print "defined in ", __PACKAGE__, "\n" 
};

MyClass::from_my_class();
Ruby
class String
  def self.from_string
    print "defined in " + self.name + $/
  end
end

String::from_string
String. from_string

Posted in ,  | Tags ,  | no comments