Possible to have `self.new` and `initialize`? Answered my own question for your entertainment!

Hi again,

I’m trying to create an optional object. If certain arguments are not met, then it should just be nil.

I thought I would accomplish this with a custom self.new method. However, it appears that you cannot have both self.new and initialize?

struct Person
  def self.new
    pp! "AAAAAAHHH"
    return nil
  def initialize
    pp! "pow"

joe = Person.new

Results in:


In the mean time I’ve just made another class method to do this, but I was caught off guard by this behaviour so I just wanted to ask and see if I had missed something.

It feels like the standard self.new method is being created because I define initialize. Thus overriding my own.


As I’m writing this I’ve been checking examples in the playground. After writing that last sentence I thought to myself, "Well, if it creates a self.new after my initialize why don’t I try defining self.new AFTER my init and maybe it will override the generated one… and it did?!

I’m going to bed happy. :smile:

Since I’ve written this all out, I figure I’ll still post it for your entertainment and maybe someone will stumble upon it in the future. Goodnight!

1 Like