在Ruby中,'new'和'initialize'之间的关系是什么?初始化时如何返回零? [英] In Ruby, what's the relationship between 'new' and 'initialize'? How to return nil while initializing?
问题描述
我想要的是:
obj = Foo.new(0) # => nil or false
这不起作用:
class Foo
def initialize(val)
return nil if val == 0
end
end
我知道在 C/C++/Java/C# 中,我们不能在构造函数中返回值.
I know in C/C++/Java/C#, we cant return a value in a constructor.
但我想知道在 Ruby 中是否有可能.
But I'm wondering whether it is possible in Ruby.
推荐答案
在 Ruby 中,'
new
' 和 'initialize
' 是什么关系?
In Ruby, what's the relationship between '
new
' and 'initialize
'?
new
通常调用 initialize
.new
的默认实现类似于:
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.
初始化时如何返回nil?
How to return nil while initializing?
我想要的是:
obj = Foo.new(0) # => nil or false
这不起作用:
class Foo
def initialize(val)
return nil if val == 0
end
end
我知道在 C/C++/Java/C# 中,我们不能在构造函数中返回值.
I know in C/C++/Java/C#, we cant return a value in a constructor.
但我想知道在 Ruby 中是否有可能.
But I'm wondering whether it is possible in Ruby.
Ruby 中没有 构造函数 这样的东西.在 Ruby 中,只有方法,它们可以返回值.
There is no such thing as a constructor in Ruby. In Ruby, there are only methods, and they can return values.
您看到的问题只是您想更改一种方法的返回值,但您正在覆盖另一种方法.如果你想改变方法bar
的返回值,你应该重写bar
,而不是其他方法.
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.
如果你想改变 Foo::new
的行为,那么你应该改变 Foo::new
:
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
但是请注意,这是一个非常糟糕的主意,因为它违反了 new
的约定,即返回一个完全初始化、功能齐全的类.
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.
这篇关于在Ruby中,'new'和'initialize'之间的关系是什么?初始化时如何返回零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!