def and undef a method

Jul 25
2008
def my_method; end # define a method
undef my_method    # remove a method

The core manual

Simple class’s variable accessor

Jul 19
2008
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"

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

Jun 16
2008
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

Convert an array to a hash

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

Dynamically Define Methods

Jan 11
2008

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

Calendar

March 2010
M T W T F S S
« Feb    
1234567
891011121314
15161718192021
22232425262728
293031  

Tags