This is just to keep note of some cool tricks ive come across, will probably be updated frequently.

Parent class detecting when it has been inherited from

class Mother
  def self.inherited(subclass)
    puts "squeezing out #{subclass}"
  end
end

class Child < Mother

end

Passing a block straight to select which determines if the method should be dispatched or not.

class Array
  def exec(method, *args, &block)
    select(&block).map { |i| i.send(method, *args) }
  end
end

Flipflop operator

1.upto(100) do |i|
  puts i if (i == 3)..(i == 15)
end

Convert numbers to other bases

>> 1234567890.to_s(2)
=> "1001001100101100000001011010010"
>> 1234567890.to_s(16)
=> "499602d2"

Add a method to all instances of a class from within the instance constructor

class Test
    def initialize
        self.class.send(:define_method, :methodname) {

        }
    end
end

Add a method to just this instance of the class (metaclass)

class Test
    def metaclass; class << self; self; end; end

    def initialize
        metaclass.instance_eval {
            define_method(:methodname) {

            }
        }
    end
end
Back