Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Faking the new operator in Ruby. IT"S A JOKE LAUGH.
module Kernel
def new(object)
if object.is_a?(Class)
object.new
else
object
end
end
def method_missing(method_name, *args, &block)
if method_name.to_s =~ /^[A-Z]/
mod =
if self.is_a?(Module)
self
else
self.class
end
klass = mod.const_get(method_name.to_s) rescue nil
if klass.is_a?(Class)
return klass.send(:new, *args, &block)
end
end
super
end
end
module NerdyC
class Person
attr_accessor :name, :email
def initialize(name, email = nil)
self.name = name
self.email = email
end
def inspect
"#{name} <#{email}>"
end
end
end
new NerdyC::Person('Christian Niles', 'christian@email.com')
# => Christian Niles <christian@email.com>
include NerdyC
new Person('Christian Niles', 'christian@email.com')
# => Christian Niles <christian@email.com>
Owner

nerdyc commented Jan 6, 2011

This code is a joke in response to my friend Alejandro's tweet, in which he asked for a 'new' operator in ruby 1.9. I casually threw together this abuse of method_missing to show him how it's done :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment