Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
969 views
in Technique[技术] by (71.8m points)

constructor - In Ruby, what's the relationship between 'new' and 'initialize'? 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...