Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created February 18, 2024 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/3eec4f60ce83dbf5ab02cb4a167a5f1b to your computer and use it in GitHub Desktop.
Save havenwood/3eec4f60ce83dbf5ab02cb4a167a5f1b to your computer and use it in GitHub Desktop.
An example of how to create a custom `new` method for all Classes or just a particular Class
class Class
def new(...)
warn 'Overriding Class#new'
instance = allocate
instance.send(:initialize, ...)
instance
end
end
class Universe
def initialize(meaning:)
@meaning = meaning
end
end
p Universe.new(meaning: 42)
#!> Overriding Class#new
#>> #<Universe:0x... @meaning=42>
class Universe
def self.new(...)
warn 'Overriding Universe::new'
instance = allocate
instance.send(:initialize, ...)
instance
end
end
p Universe.new(meaning: 42)
#!> Overriding Universe::new
#>> #<Universe:0x... @meaning=42>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment