Skip to content

Instantly share code, notes, and snippets.

@nerdyc
Created January 6, 2011 01:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nerdyc/767364 to your computer and use it in GitHub Desktop.
Save nerdyc/767364 to your computer and use it in GitHub Desktop.
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>
@nerdyc
Copy link
Author

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