def and undef a method
Jul 25
2008
2008
Comments Off
def my_method; end # define a method undef my_method # remove a method
my web space
def my_method; end # define a method undef my_method # remove a method
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"
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)
class Array def to_h arr = self.dup if arr.size % 2 == 0 Hash[*arr] else Hash[*arr < < nil] end end end
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