In Ruby, what's the relationship between 'new' and 'initialize'? How to return nil while initializing?

40,605

Solution 1

In Ruby, what's the relationship between 'new' and 'initialize'?

new typically calls initialize. The default implementation of new is something like:

class Class
  def new(*args, &block)
    obj = allocate

    obj.initialize(*args, &block)
    # actually, this is obj.send(:initialize, …) because initialize is private

    obj
  end
end

But you can, of course, override it to do anything you want.

How to return nil while initializing?

What I want is:

obj = Foo.new(0)  # => nil or false

This doesn't work:

class Foo
  def initialize(val)
    return nil if val == 0
  end
end

I know in C/C++/Java/C#, we cant return a value in a constructor.

But I'm wondering whether it is possible in Ruby.

There is no such thing as a constructor in Ruby. In Ruby, there are only methods, and they can return values.

The problem you are seeing is simply that you want to change the return value of one method but you are overriding a different method. If you want to change the return value of method bar, you should override bar, not some other method.

If you want to change the behavior of Foo::new, then you should change Foo::new:

class Foo
  def self.new(val)
    return nil if val.zero?
    super
  end
end

Note, however, that this is a really bad idea, since it violates the contract of new, which is to return a fully initialized, fully functioning instance of the class.

Solution 2

There are important differences between the two methods.

new is a class method, which generally creates an instance of the class (this deals with the tricky stuff like allocating memory that Ruby shields you from so you don't have to get too dirty).

Then, initialize, an instance method, tells the object to set its internal state up according to the parameters requested.

Either of these can be overridden depending on what you want. For example, Foo.new might actually create and return an instance of FooSubclass if it needs to be clever enough to do that.

However, often it's better to delegate use cases like these to other class methods which are more explicit about what they do, for example Foo.relating_to(bar). Breaking other peoples expectations about what methods like new should do will confuse people more than it will help them in the long run.

As an example, look at the implementation of Singleton, a module which allows only one instance of a particular class to exist. It makes the new method private, and exposes an instance method which either returns the existing instance of the object, or calls new if it hasn't been created yet.

Solution 3

You can something like this:

class Foo

  def self.init(val)
    new(val) unless val == 0
  end

  def initialize(val)
    #...
  end
end

Example of usage:

obj = Foo.init(0)
 => nil
obj = Foo.init(5)
 => #<Foo:0x00000002970a98>

Solution 4

Wanting to do

class Foo
  def initialize(val)
    return nil if val == 0
  end
end

would make for inconsistent code.

If you had

class Foo
  def initialize(val)
    return nil if val == 0
    @val = val
    @bar = 42
  end
end

what would you want to get back if you did Foo.new(1)? Would you want 42 (the return value for Foo#initialize), or a foo object? If you want a foo object for Foo.new(1), then why would you expect return nil to make Foo.new(0) return nil?

Share:
40,605
Chris Xue
Author by

Chris Xue

Updated on July 08, 2022

Comments

  • Chris Xue
    Chris Xue almost 2 years

    What I want is:

    obj = Foo.new(0)  # => nil or false
    

    This doesn't work:

    class Foo
      def initialize(val)
        return nil if val == 0
      end
    end
    

    I know in C/C++/Java/C#, we cant return a value in a constructor.

    But I'm wondering whether it is possible in Ruby.

  • OpenCoderX
    OpenCoderX over 11 years
    In your example does this call new also?
  • Flexoid
    Flexoid over 11 years
    If you mean the example when we call init with 0, then no, the new won't be invoked.
  • Jörg W Mittag
    Jörg W Mittag over 8 years
    self is Foo there. Try class Foo; p self end # => Foo
  • Todd
    Todd over 5 years
    Instead of simply stating that something is bad, would you care to offer the OP a better designed solution? Perhaps something like Metz's after_initialize pattern? A validator? Etc.