Created
February 18, 2024 00:45
-
-
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
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
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