Created
January 6, 2011 01:30
-
-
Save nerdyc/767364 to your computer and use it in GitHub Desktop.
Faking the new operator in Ruby. IT"S A JOKE LAUGH.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :)